Simplest Login and Logout example in JSP

This JSP example shows you how to login and logout the session between JSP pages.
JSP provide an implicit object that is session in which use to save the data specific
by the particular user. Now in this tutorial we are create application takes an
user login from that having user name and password, in this example saves an user
session that
invalidate with session.invalidate() function. We will display the saved data to the user in another page.
Fallowing is the code of the simple JSP file is login.jsp that takes the input from
user.
The code of the program is given below:
<html>
<head>
<title>User Login</title>
</head>
<br>
<body Bgcolor ="#0099cc"><hr><hr>
<form method="POST" action="sessionAction.jsp">
<p><b>UserName:</b> <input type="text" name="UserName" size="10"></p>
<p><b>Password:</b> <input type="Password" name="Password" size="10"></p>
<p><input type="submit" value="Submit" name="submit"><input type= "reset" value="Reset" name="reset"></p><hr><hr>
</form>
</body>
</html>
|
The above login page prompts the user to enter his or her name. Once the user clicks on the submit
button that time sessionAction.jsp is called. The JSP sessionAction.jsp retrieves the user name from request attributes and saves into the user session using the function:
| session.setAttribute("UserName", request.getParameter("UserName")); |
The above Action JSP page saves the UserName into the session object and displays a link to next pages
that is sessionAction.jsp. When user clicks on the "Next Page to view session value" link, the JSP page
sessionAction.jsp displays the user name to the user. Here is the code of sessionAction.jsp:
Here is the code of sessionAction.jsp:
<%@page import="java.util.*" %>
<%String str = request.getParameter("UserName");
session.setAttribute("UserName", request.getParameter("UserName"));%>
Welcome to <%= session.getAttribute( "UserName" ) %>
<% if (session.getAttribute("UserName").equals("")){%>
<a href="login.jsp"><b>Login </b></a>
<%}
else{%>
<a href="logout.jsp"><b>Logout</b></a>
<%}
%>
|
The function <%= session.getAttribute( "UserName" ) %>
is used to retrieve the user name saved in the session.
| <%= session.getAttribute( "UserName" ) %> |
The code of the program is given below:
<%@page import="java.util.*" %>
<%session.invalidate();%>
You have logged out. Plese
<a href="login.jsp"><b>Login</b></a>
|
The function <%session.invalidate();%> is used to
invalidate the user login session.
| <%session.invalidate();%> |
The output of the program is given below:

The output of the program is given below:

The output of the program is given below:

Download Source Code

|