18
Jan

First of all, you have to  create a simple login form with plain html tags and name it as login.jsp or any-name.jsp and
save it in your apache-tomcat’s webapps folder. The script for creating login.jsp given below:

[sourcecode language="html"]
<html>
<head><title>Login</title>
</head>
<body>
<form action="main_page.jsp">
<table>
<tr><th colspan="2">Login</th></tr>
<tr>
<td>Username</td><td>:<input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td>Password</td><td>:<input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td>&nbsp;</td><td><input type="submit" name="btn_submit" id="btn_submit" value="Login" /></td>
</tr>
</table>
</form>
</body>
</html>
[/sourcecode]

After that, you have to add session function <% session.invalidate(); %> at the top of this login.jsp file for clearing existing session variables.

After that, you have to create the action page “main_page.jsp” (<form action=”main_page.jsp”>) and paste the following code in it:

<html>
<head><title>Main Page</title></head>
<body>

[sourcecode language="java"]
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if( username.equals("rajeev") && password.equals("rajeev123") ) {
session.setAttribute( "sess_username", username );

%>

[/sourcecode]

<b>Welcome <%=session.getAttribute(“sess_username”) %>. <a href=”login.jsp”>Logout</a>
<% }else{ %>
<b>Incorrect username or password. <a href=”login.jsp”>Retry</a> </b>
<% } %>
</body>
</html>

and save this file in the apache-tomcat’s webapps folder.
<%
String username = request.getParameter(“username”);
String password = request.getParameter(“password”);
%>
The above two lines are used to accept values from login.jsp form (username and password).

The the following lines are used to check whether the username is “rajeev” and password is “rajeev123″ and if the username and password are correct,
then the username will be stored in a session variable “sess_username” and echo a welcome user message and a logout link.
<%
if( username.equals(“rajeev”) && password.equals(“rajeev123″) ) {
session.setAttribute( “sess_username”, username );
%>
<b>Welcome <%=session.getAttribute(“sess_username”) %>. <a href=”login.jsp”>Logout</a>
If the username and password are incorrect then the script will echo “incorrect username or password” with a retry link.

Rajeev Pillai
Posted by on 18 Jan 2010 by Rajeev Pillai in JSP

Add reply

*