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" %>
<%-- Remove Session Object Variables on Log Out and New Visit--%>
<% session.removeAttribute("username"); session.removeAttribute("type");%>
${fn:escapeXml(param.errorMsg)}
[/sourcecode]
Authenticate Page (authenticate.jsp)
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.
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.
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.
Code: authnticate.jsp
[sourcecode language=”coldfusion” title=”authenticate.jsp”]
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ page import = "java.sql.*,java.util.*" %>
<%-- Validation Phase--%>
<%--
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.
SELECT LT FROM LOGIN
WHERE LUN = ? AND LP = ?
–%>
<%-- If valid username and password is given, then row count will be 1, else row count will be 0.
–%>
<%-- Get Type of User Field Value and store in variable LType
–%>
<%-- Setting Session Object Variables
<%
session.setAttribute("username", request.getParameter("UN"));
%>
–%>
<%-- Setting Session Object Variable Value Based on type of User Login
<%session.setAttribute("type","Teacher"); %>
<%session.setAttribute("type","Student"); %>
<%session.setAttribute("type","Admin"); %>
–%>
<%-- Static Page Code without Database--%>
<%session.setAttribute("type","Admin");
session.setAttribute("username", request.getParameter("UN")); %>
<%session.setAttribute("type","Teacher");
session.setAttribute("username", request.getParameter("UN")); %>
<%session.setAttribute("type","Student");
session.setAttribute("username", request.getParameter("UN")); %>
<%-- Default Condition--%>
[/sourcecode]
Welcome Page
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.
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).
Code: AWelcome.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.*" %>
<%-- 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.*" %>
<%-- 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:
Hope this article will help you in understanding how to implement sessions in JSP.
are you feel this code is so complex
It is basically not so, only it seems because of authentication via database code.
Session code is very simple:
login page code contains only following code related to sessions :
Authentication code contains:
And Main Page contains:
else all code is default jsp and html code.
You can modify the above code as per you scenario.
Nice writeup bro! . I came looking for JSP authentication and landed on your page. I guess you’re using taglibs. Looks neat and uncluttered. Will give it a try.
Thanks and Cheers
Matthew
Thanks !
And ya I am using taglibs, this worked for me.
Regards
Sakun Sharma