Maintaining Sessions in JSP

Download PDF Version

We need sessions for security purpose and multiuser support. Here we are going to use sessions for security in the following manner:

1. Restrict user to open admin panel.
2. Restrict specific type of user to open some other pages.
3. Restrict user from opening pages after logging out of the console.

In JSP we use session objects to do the needful. With the help of this session object, we can define variables in that session.

Case Scenario: We have an application with three types of console – Student, Teacher and Admin. We want that whenever any kind of member log in, that user can access only its console related pages. That user cannot open other user’s pages. We also want that, when ever user log’s out, that user cannot open pages by clicking back button.

Solution: To solve the problem given in above case scenario, we will use session objects. To demonstrate working of this we will need 4 web pages – Login, Authenticate, Welcome and Console.

Login Page (login.jsp)

In login page, we will ask for username and password of the user. We will create this page using simple HTML tags with Form tag. After user successfully enters its username and password, we will submit that form using POST method to Authenticate.jsp page. This page will be JSP page because we will include JSP code for session object removal. (We will discuss about session object removal in later section [Welcome Page])

Code: login.jsp

[sourcecode language=”html” title=”login.jsp”]


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>




Sakun Sharma Blog: JSP Sessions – Login<title> <link rel="stylesheet" href="styles.css" type="text/css" /> </head><br /> <body data-rsssl=1><br /> <%-- Remove Session Object Variables on Log Out and New Visit--%><br /> <% session.removeAttribute("username"); session.removeAttribute("type");%></p> <p> <font color="red"><br /> ${fn:escapeXml(param.errorMsg)}<br /> </font> </p> <form action="authenticate.jsp" method="post"> <table> <tr> <th colspan="2"> <h4>Login</h4> </th> </tr> <tr> <td><center>Username</center></td> <td><input type="text" name="UN" id="UN" value="${fn:escapeXml(cookie.UN.value)}"/></td> </tr> <tr> <td><center>Password</center></td> <td><input type="password" name="PWD" id="PWD" value="${fn:escapeXml(cookie.PWD.value)}" /></td> </tr> <tr> <td colspan="2"><center><input type="submit" name="BLI" id="BLI" value="Enter"/></center></td> </tr> </table> </form> <p></body><br /> </html></p> <p>[/sourcecode]<br /> </p> <h2>Authenticate Page (authenticate.jsp)</h2> <p align="justify"> This page will be JSP page. In this page we will authenticate username and password provided by user with our database records. As we don’t have database here, we will simple check username and password with static code directly defined in the page itself. But I will also include code of validating from database. </p> <p align="justify"> After username and password has been successfully validated, we will create session object for the user. In the code given below you can see that we have defined two session variables – Username and Type. Username variable contains username of user and type contains the type of user it is (Admin, Student or Teacher). In this page, we are creating session objects to be used later in welcome page for authorizing the user. </p> <p align="justify"> Now, we have three different welcome pages – Admin Welcome, Student Welcome and Teacher Welcome. Based on type of user, we will redirect user to his specific welcome page. </p> <h3>Code: authnticate.jsp</h3> <p>[sourcecode language=”coldfusion” title=”authenticate.jsp”]</p> <p><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><br /> <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %><br /> <%@ page import = "java.sql.*,java.util.*" %></p> <p><%-- Validation Phase--%><br /> <c:if test="${empty param.UN || empty param.PWD}"><br /> <c:redirect url="login.jsp" ><br /> <c:param name="errorMsg" value="You must enter a User Name and Password." /><br /> </c:redirect><br /> </c:if></p> <p><%-- See if the user name and password combination is valid from database. If not, redirect back to the login page with a message. I am commenting all the database related code because we are going to test on static code without database. Static Page Code Without Database is given at the end of this page. <sql:setDataSource dataSource="jdbc/MyDataSource"/><br /> <sql:query var="STDInfo"><br /> SELECT LT FROM LOGIN<br /> WHERE LUN = ? AND LP = ?<br /> <sql:param value="${param.UN}" /><br /> <sql:param value="${param.PWD}" /><br /> </sql:query><br /> –%><br /> <%-- If valid username and password is given, then row count will be 1, else row count will be 0. <c:if test="${STDInfo.rowCount == 0}"><br /> <c:redirect url="login.jsp" ><br /> <c:param name="errorMsg" value="The User Name or Password you entered is not valid." /><br /> </c:redirect><br /> </c:if></p> <p>–%></p> <p><%-- Get Type of User Field Value and store in variable LType <c:forEach var="row" items="${STDInfo.rowsByIndex}"><br /> <c:forEach var="column" items="${row}"><br /> <c:set var = "LType" value='${column}'/><br /> </c:forEach><br /> </c:forEach><br /> –%></p> <p><%-- Setting Session Object Variables <% session.setAttribute("username", request.getParameter("UN")); %><br /> –%><br /> <%-- Setting Session Object Variable Value Based on type of User Login <c:if test="${LType == 'Teacher'}"><br /> <%session.setAttribute("type","Teacher"); %><br /> <c:redirect url="TWelcome.jsp" ><br /> </c:redirect><br /> </c:if></p> <p><c:if test="${LType == 'Student'}"><br /> <%session.setAttribute("type","Student"); %><br /> <c:redirect url="SWelcome.jsp" ><br /> </c:redirect><br /> </c:if></p> <p><c:if test="${LType == 'Admin'}"><br /> <%session.setAttribute("type","Admin"); %><br /> <c:redirect url="AConsole.jsp" ><br /> </c:redirect><br /> </c:if><br /> –%></p> <p><%-- Static Page Code without Database--%><br /> <c:if test="${ param.UN ==’admin’ && param.PWD ==’admin123.,’}"><br /> <%session.setAttribute("type","Admin"); session.setAttribute("username", request.getParameter("UN")); %><br /> <c:redirect url="AWelcome.jsp" ><br /> </c:redirect><br /> </c:if></p> <p><c:if test="${ param.UN ==’teacher’ && param.PWD ==’tea123.,’}"><br /> <%session.setAttribute("type","Teacher"); session.setAttribute("username", request.getParameter("UN")); %><br /> <c:redirect url="TWelcome.jsp" ><br /> </c:redirect><br /> </c:if></p> <p><c:if test="${ param.UN ==’student’ && param.PWD ==’stu123.,’}"><br /> <%session.setAttribute("type","Student"); session.setAttribute("username", request.getParameter("UN")); %><br /> <c:redirect url="SWelcome.jsp" ><br /> </c:redirect><br /> </c:if></p> <p><%-- Default Condition--%><br /> <c:redirect url="login.jsp" ><br /> <c:param name="errorMsg" value="Invalid Login Type, please contact your Administrator" /><br /> </c:redirect></p> <p>[/sourcecode]<br /> </p> <h2>Welcome Page</h2> <p align="justify"> In welcome page, we will check for type of user opening the page based on which welcome page is being opened. For example, if student is opening teachers welcome page, it should return error and log user out, and if it’s opening student welcome page, then it should open successfully. </p> <p align="justify"> In this page we will also have link to console page. We will use this console page to test back button security setting. (How and Why is explained in later section). </p> <h3>Code: AWelcome.jsp</h3> <p>[sourcecode language=”html” title=”AWelcome.jsp”]<br /> <?xml version="1.0" encoding="ISO-8859-1" ?><br /> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><br /> <%@ page import = "java.sql.*,java.util.*" %><br /> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><br /> <html xmlns="http://www.w3.org/1999/xhtml"><br /> <head><br /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><br /> <title>Sakun Sharma: Maintaining Sessions in JSP

<%-- Authorizing User and its type for this page.--%>
<% String State = ""; if (session.getAttribute("username")!=null && session.getAttribute("username")!="") { State = session.getAttribute("username").toString(); if (session.getAttribute("type")!= "Admin") { response.sendRedirect(request.getContextPath() + "/login.jsp?errorMsg=Invalid+Page+Requested."); } } else { response.sendRedirect(request.getContextPath() + "/login.jsp?errorMsg=Session Closed or Session Timout."); } %>

Welcome Admin

Admin Console

Log Out



[/sourcecode]

Code:AConsole.jsp

[sourcecode language=”html” title=”AWelcome.jsp”]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import = "java.sql.*,java.util.*" %>




Sakun Sharma: Maintaining Sessions in JSP

<%-- Authorizing User and its type for this page.--%>
<% String State = ""; if (session.getAttribute("username")!=null && session.getAttribute("username")!="") { State = session.getAttribute("username").toString(); if (session.getAttribute("type")!= "Admin") { response.sendRedirect(request.getContextPath() + "/login.jsp?errorMsg=Invalid+Page+Requested."); } } else { response.sendRedirect(request.getContextPath() + "/login.jsp?errorMsg=Session Closed or Session Timout."); } %>

Admin Console Page

Admin Welcome Page

Log Out



[/sourcecode]

Student Welcome

In student welcome page the only difference in authorizing code will be the value of type of user.
Instead of: if (session.getAttribute(“type”)!= “Admin”)
It will be: if (session.getAttribute(“type”)!= “Student”)

Similarly the code will be for student console, teacher welcome and teacher console. The method to authorize will remain same only.

Removing Session Object Variables

After clicking “Log Out” link, page will be re-directed to Login page. In login page we have added following code:

[sourcecode language=”coldfusion”]
<%-- Remove Session Object Variables on Log Out and New Visit--%>
<% session.removeAttribute("username"); session.removeAttribute("type");%>
[/sourcecode]

This code is used to remove the session objects created during the login process in authentication.jsp page. As these objects are deleted, this session will be no more valid session. Now when we will click on back link, it will open previous page successfully (not in all browsers) but will not function. It will open that page successfully because it’s being opened from cache memory not from server (not applicable with all browsers), but it will not function. To test this, either re-load page by clicking refresh button or click on console.jsp link it will re-direct to login page displaying an error message “Invalid Session”.

Default Username’s and Password:

Username
Password
Login Type
student
stu123.,
Student Login
teacher
tea123.,
Teacher Login
admin
admin123.,
Admin Login

Hope this article will help you in understanding how to implement sessions in JSP.