J2EE Programming

Hands On No. 6 : Concept of Request Dispatching

Source Code of index.html

<html>
<head>
<title>Log In Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name='frmmain' action="checkLogin" method="post">
<table width='500px' align='center'>
<tr>
<td>Enter User Name</td>
<td><input type="text" name='txtuname'></td>
</tr>
<tr>
<td>Enter Password </td>
<td><input type="password" name='txtupassword'></td>
</tr>

<tr>
<td></td>
<td><input type="submit" value='LogIn'></td>
</tr>
</table>
</form>
</body>
</html>

Source Code of checkLogin Servlet

String uname = request.getParameter("txtuname");
String upassword = request.getParameter("txtupassword");
if((uname.equals("admin"))&& (upassword.equals("admin")))
{
RequestDispatcher rd=request.getRequestDispatcher("viewUser");
rd.forward(request, response);
}
else
{
out.print(" <table width='500px' align='center'><tr><td align=center>Wrong Username or Password</td></tr></table>");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}

Source Code of viewUser Servlet

try
{
String s = request.getParameter("txtuname");
if(s.equals(""))
{
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.forward(request, response);
}
else
{
out.print(" <table width='500px' align='center'><tr><td align=center>Welcome " + s + "</td></tr></table>");
}
}
catch(Exception e)
{
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.forward(request, response);
}