postheadericon Example of requestdispatcher

index.jsp

<html>
<head>
<title>MySqlLogin</title>
<style>
.abc
{
background:#ababff;
position:absolute;
top:2in;
hieght:200px;
width:300px;
left:5in;
border-style:solid;
}
</style>
</head>



<body>

<div class="abc"  id="f1">
<br>
<form method="POST" action="doLogin">
<table align="center">
<tr>
<td colspan=2 align=center>
Login
<hr>
</td>
</tr>

<tr>
<td>User Name : </td>
<td><input type="text" name="txtUsr"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="txtPwd"></td>
</tr>

<tr>
<td colspan=2 align=center>
<hr>
<input type="submit" value="Login">
<input type="reset" value="Reset">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>



admin.jsp

<html>
<head>
<title>MySqlLogin</title>
<style>
.abc
{
background:#ababff;
position:absolute;
top:2in;
hieght:200px;
width:300px;
left:5in;
border-style:solid;
}
</style>
</head>

<body>

<div class="abc"  id="f1">
welcome to admin
</div>
</body>
</html>



MySqlLogin.java

package bsr;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;


@WebServlet("/doLogin")
public class MySqlLogin extends HttpServlet {

     
    public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException
    {
    response.setContentType("text/html");
PrintWriter out= response.getWriter();

String className= "com.mysql.jdbc.Driver";
String url= "jdbc:mysql://localhost:3306/test";
String user= "root";
String password= "admin";

String txtUsr= request.getParameter("txtUsr");
String txtPwd= request.getParameter("txtPwd");

Connection con;
PreparedStatement ps;
ResultSet rs;

try
{
Class.forName(className);
con= DriverManager.getConnection(url, user, password);

//String sql= "SELECT usr FROM login WHERE usr = '"+txtUsr+"' AND pwd = '"+txtPwd+"'";
String sql= "SELECT usr FROM login WHERE usr = ? AND pwd = ?";

ps=con.prepareStatement(sql);

ps.setString(1, txtUsr);
ps.setString(2, txtPwd);

rs= ps.executeQuery();

ServletContext context= getServletContext();
if(rs.next())
{
String n= rs.getString("usr");
RequestDispatcher rd= context.getRequestDispatcher("/admin.jsp");
rd.forward(request, response);
}
else
{

RequestDispatcher rd= context.getRequestDispatcher("/index.jsp");
out.println("<center><font color=red>invalid user name or password</font>");
rd.include(request, response);
}

con.close();
ps.close();
rs.close();
}

catch(SQLException sx)
{
out.println(sx);
}
catch(ClassNotFoundException cx)
{
out.println(cx);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}


0 comments:

Follow by Email

Blog Archive

Total Pageviews

© BipinRupadiya.com. Powered by Blogger.