Session Management in Java Servlet Web Applications is a very interesting topic. Session in Java Servlet are managed through different ways, such as Cookies, HttpSession API, URL rewriting etc. This is the third article in the series of Web Applications tutorial in Java, you might want to check out earlier two articles too.
This article is aimed to explain about session management in servlets using different techniques and with example programs.
HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to process and they can’t identify if it’s coming from client that has been sending request previously. But sometimes in web applications, we should know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client. Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. There are several ways through which we can provide unique identifier in request and response.
User Authentication - This is the very common way where we user can provide authentication credentials from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it wont work if the same user is logged in from different browsers.
HTML Hidden Field - We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session.
URL Rewriting - We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters.
Cookies - Cookies are small piece of information that is sent by web server in response header and gets stored in the browser cookies. When client make further request, it adds the cookie to the request header and we can utilize it to keep track of the session. We can maintain a session with cookies but if the client disables the cookies, then it won’t work.
Session Management API - Session Management API is built on top of above methods for session tracking. Some of the major disadvantages of all the above methods are:
That’s why we need Session Management API and J2EE Servlet technology comes with session management API that we can use.
Cookies are used a lot in web applications to personalize response based on your choice or to keep track of session. Before moving forward to the Servlet Session Management API, I would like to show how can we keep track of session with cookies through a small web application. We will create a dynamic web application ServletCookieExample with project structure like below image. Deployment descriptor web.xml of the web application is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ServletCookieExample</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Welcome page of our application is login.html where we will get authentication details from user.
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
Here is the LoginServlet that takes care of the login request.
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "Pankaj";
private final String password = "journaldev";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
Cookie loginCookie = new Cookie("user",user);
//setting cookie to expiry in 30 mins
loginCookie.setMaxAge(30*60);
response.addCookie(loginCookie);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
Notice the cookie that we are setting to the response and then forwarding it to LoginSuccess.jsp, this cookie will be used there to track the session. Also notice that cookie timeout is set to 30 minutes. Ideally there should be a complex logic to set the cookie value for session tracking so that it won’t collide with any other request.
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
String userName = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
if(userName == null) response.sendRedirect("login.html");
%>
<h3>Hi <%=userName %>, Login successful.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
Notice that if we try to access the JSP directly, it will forward us to the login page. When we will click on Logout button, we should make sure that cookie is removed from client browser.
package com.journaldev.servlet.session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Cookie loginCookie = null;
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")){
loginCookie = cookie;
break;
}
}
}
if(loginCookie != null){
loginCookie.setMaxAge(0);
response.addCookie(loginCookie);
}
response.sendRedirect("login.html");
}
}
There is no method to remove the cookie but we can set the maximum age to 0 so that it will be deleted from client browser immediately. When we run above application, we get response like below images.
Servlet API provides Session management through HttpSession
interface. We can get session from HttpServletRequest object using following methods. HttpSession allows us to set objects as attributes that can be retrieved in future requests.
Some of the important methods of HttpSession are:
getAttributeNames()
, removeAttribute(String name)
and setAttribute(String name, Object value)
.getLastAccessedTime()
method.getMaxInactiveInterval()
method.When we use HttpServletRequest getSession() method and it creates a new request, it creates the new HttpSession object and also add a Cookie to the response object with name JSESSIONID and value as session id. This cookie is used to identify the HttpSession object in further requests from client. If the cookies are disabled at client side and we are using URL rewriting then this method uses the jsessionid value from the request URL to find the corresponding session. JSESSIONID cookie is used for session tracking, so we should not use it for our application purposes to avoid any session related issues. Let’s see example of session management using HttpSession object. We will create a dynamic web project in Eclipse with servlet context as ServletHttpSessionExample. The project structure will look like below image. login.html is same like earlier example and defined as welcome page for the application in web.xml LoginServlet servlet will create the session and set attributes that we can use in other resources or in future requests.
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "password";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins
session.setMaxInactiveInterval(30*60);
Cookie userName = new Cookie("user", user);
userName.setMaxAge(30*60);
response.addCookie(userName);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
Our LoginSuccess.jsp code is given below.
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
String user = null;
if(session.getAttribute("user") == null){
response.sendRedirect("login.html");
}else user = (String) session.getAttribute("user");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
}
}
%>
<h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
<br>
User=<%=user %>
<br>
<a href="CheckoutPage.jsp">Checkout Page</a>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
When a JSP resource is used, container automatically creates a session for it, so we can’t check if session is null to make sure if user has come through login page, so we are using session attribute to validate request. CheckoutPage.jsp is another page and it’s code is given below.
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
if(session.getAttribute("user") == null){
response.sendRedirect("login.html");
}
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<h3>Hi <%=userName %>, do the checkout.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
Our LogoutServlet code is given below.
package com.journaldev.servlet.session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session != null){
session.invalidate();
}
response.sendRedirect("login.html");
}
}
Notice that I am printing JSESSIONID cookie value in logs, you can check server log where it will be printing the same value as Session Id in LoginSuccess.jsp Below images shows the execution of our web application.
As we saw in last section that we can manage a session with HttpSession but if we disable the cookies in browser, it won’t work because server will not receive the JSESSIONID cookie from client. Servlet API provides support for URL rewriting that we can use to manage session in this case. The best part is that from coding point of view, it’s very easy to use and involves one step - encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled. We can encode URL with HttpServletResponse encodeURL()
method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL()
method. We will create a similar project like above except that we will use URL rewriting methods to make sure session management works fine even if cookies are disabled in browser. ServletSessionURLRewriting project structure in eclipse looks like below image.
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "password";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins
session.setMaxInactiveInterval(30*60);
Cookie userName = new Cookie("user", user);
response.addCookie(userName);
//Get the encoded URL string
String encodedURL = response.encodeRedirectURL("LoginSuccess.jsp");
response.sendRedirect(encodedURL);
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
//allow access only if session exists
String user = null;
if(session.getAttribute("user") == null){
response.sendRedirect("login.html");
}else user = (String) session.getAttribute("user");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
}
}else{
sessionID = session.getId();
}
%>
<h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
<br>
User=<%=user %>
<br>
<!-- need to encode all the URLs where we want session information to be passed -->
<a href="<%=response.encodeURL("CheckoutPage.jsp") %>">Checkout Page</a>
<form action="<%=response.encodeURL("LogoutServlet") %>" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
String userName = null;
//allow access only if session exists
if(session.getAttribute("user") == null){
response.sendRedirect("login.html");
}else userName = (String) session.getAttribute("user");
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<h3>Hi <%=userName %>, do the checkout.</h3>
<br>
<form action="<%=response.encodeURL("LogoutServlet") %>" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
package com.journaldev.servlet.session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
}
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session != null){
session.invalidate();
}
//no encoding because we have invalidated the session
response.sendRedirect("login.html");
}
}
When we run this project keeping cookies disabled in the browser, below images shows the response pages, notice the jsessionid in URL of browser address bar. Also notice that on LoginSuccess page, user name is null because browser is not sending the cookie send in the last response.
If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.
Thats all for session management in java servlets, we will look into Servlet Filters and Listeners and Cookies in future articles. Update: Check out next article in the series Servlet Filter.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
i had implemented the example following above steps. coming to this line : response.sendRedirect(“LoginSuccess.jsp”); i was getting http 404 error .can you please help me.
- krishna
404 error comes when requested resource is not available, please check if LoginSuccess.jsp is present in the root of your web application. Are you deploying directly to Tomcat from Eclipse or you are exporting as WAR file and then deploying it?
- Pankaj
Hi, Interesting article. I’ve tried it and it does work. I thought that it was not possible to set a session attribute and then do a response.sendRedirect without loosing the attribute set in the session. /Gunnar
- Gunnar Boström
It’s because the session is still valid and when client send further requests and we call getSession(), we get the same session and it has the attribute in it.
- Pankaj
how to maintain session between login and logout if i DO session.invalidate(); for logout page but when i press back button browser at the time show information between login and logout….? plz sir how to stop show information after log-out plz tell me…. i m waiting u response ……
- naveen
You need to tell browser not to cache the page, you can do this with below code.
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0. ``` `` response.setDateHeader("Expires", 0); // Proxies. `If there are several pages, best way to do is create a Filter where you will add these headers in response and configure the filter for all the URIs you don't want to be cached.` `` ```
- Pankaj
Hi, the example which you have demonstrated for URLRewriting is not exact.The idea of rewriting is you will append the sessionid which you have set in session.setatttribute along with the response.But you have not done anything like that in URL rewriting.Please clarify.
- indra
Hi Indra, The concept of URL rewriting is to add the session id in the URLs, servlet response encodeURL and encodeRedirectURL does the same thing for us behind the scene IF cookies are disabled. So basically it’s the same thing where we are using Servlet API for URL rewriting.
- Pankaj
Thanks for your tutorials. Very well-prepared and explained. Look forward to reading your future posts.
- michael
Thanks Michael, these positive comments push me in continuing my effort.
- Pankaj
Fantastic Job broo… keep posting
- Gowtham
Can you please explain shopping cart using 3-tier architecture in netbeans 7.3.1?
- jagroop singh
Thanks Pankaj Great way to explain with the output, it really helps the beginner to learn new things. Looking forward to some new examples on Springs and other Technology.
- James
hi, will u please provide some examples to insert login and logout timings into SQL Server database using jsps? Thank you
- deepthi
JSPs should not contain business logic, that is a bad programming model. For DB Operations example read this post https://www.journaldev.com/1997/servlet-example-in-java-with-database-connection-and-log4j-integration
- Pankaj
I must be missing something, because I don’t understand why you need to store the user’s name in a cookie. Couldn’t this simply be set in the session (session.setAttribute(“user”, user) )? Also, isn’t this still vulnerable to a theft of the session ID (i.e., if somebody simply steals my session ID cookie, they will then authenticate as me)? Am I correct in thinking that the session data remains stored on the server and is not available on the client? Thanks.
- H S J
HttpSession work on Cookies only and it adds a cookie jsessionid with some random generated value for the session id. Please read the post again clearly, cookies can be used for session management but as you stated that if the logic is simple then anyone can hack it. That’s why we should use the Servlet API HttpSession for session management.
- Pankaj
Your tutorial is very resourceful for beginners like me. If you dont mind can i suggest if you could explain the concepts while using different variable names. For eg. in URL rewriting you have used the variable “user” repeatedly for different purposes to “setattribute”, “cookie request” etc. If you could use different variables like user, uid, usid etc. it would be easier for beginners like me to understand the code in one go. Thanks, Vinay Shetty
- Vinay Shetty
also can you please explain this line. " for(Cookie cookie : cookies) " What does this line do in a for loop? I don’t know about this kind of syntax…
- Vinay Shetty
This is the improved for loop where we can traverse through collection or array easily. Its as replacement of for(int i=0; i
- Pankaj
Hmm makes sense, I will try to keep different variable names going forward.
- Pankaj
Hi Pankaj, Nice explanation. Keep up the good work.
- Yuga
hi Pankaj, thanks for your tutorial :D but i have problem,in chrome it doesn’t work. pliz help me :)
- David
what do you mean that it doesn’t work in Chrome?
- Pankaj
Its General.Use Firefox or IE instead.
- jagdish tiwari
with your tutorial script,in firefox has working. but in chrome the url cannot rewrite session id. thanks
- David
i want to create session id and that id will stored into a database
- vajjapelli raju
Thanks very much for the article, this is very thorough and informative. I have two questions if I may. First, you mentioned that by using url encoding, we can manage session data even if cookies are disabled. In the code, you still use cookies though - why is it that it’s possible to use cookies with url encoding ? My second question, is it necessary to use Java code in jsp pages to retrieve cookie information ? The data couldn’t be retrieved by e.g. javascript ? Thank you
- Brian Forbes
We are still using Cookie because we don’t know if the Client browser accepts Cookies or not. So URL rewriting will come for rescue when cookies are disabled for any browser. Regarding retrieving Cookies in JSP pages, we should never use Scriptlets. Since it’s a example, I am using Java code to keep it simple and not overwhelm with lots of information. We can use JSP EL cookie implicit object for this. Read more at https://www.journaldev.com/2064/jsp-expression-language-el-example-tutorial
- Pankaj
Thanks for your reply ! This makes sense. Thanks for the excellent article, very well written and easy to understand.
- Brian Forbes
Hi Pankaj, What happens if the user forgets to logout/closes the browser and login from another browser or machine? Is it being handled and how is it handled?
- Ricky
Same browser logins depend on cookies timeout. For different browser and machine, you need to login again because cookies are not there.
- Pankaj
Hi Pankaj, My question is from URL Rewriting. Question is, Suppose a session object is created at server side and we use URL Rewriting for maintaining session. After that I close my browser but session object at the server side is still there(not timed out). then again I open the browser goto the history and click on the link in which Jsesionid is attached. I still get acccess to the resource(either cookies enabled or disabled). Even though I copy the link and paste it to another browser then also i access due to publicly supplying jsessionid as url. So i need help how I make website secure while I using URLRewriting…
- Rahul Kumar
In that case, you can keep request client IP and browser information in the session attributes and when request arrives, check them in the filter to make sure they match.
- Pankaj
Consider using hidden form fields instead for session tracking. These dont show up in the url
- andrew
Pankaj, I always learn new things from your article. Super work !!!
- shahrooh
your tutorial is very good. example are also good. provide some real time example (on authentication, session, logout and others that is used in making site) like we making real time company project. we take care of all these things that is mention above(auth, session etc…) in project. so we can know how it work in real time. like how facebook,twitter session works.
- Ankur
Real life projects are more complex and if I put 10K lines of code here, that will not be a guide or tutorial. You should knows the basics and have the idea of how things work and then build over it based on your requirements.
- Pankaj
For a newbie it is awesome tutorial to understand how session works. And if we talk about spring and struts f/w’s , they are also using this type of mechanisms in optimized way. Keep it up pankaj…
- Sagar Mali
Hi, I tried this example. After successfully loged in, when i close the browser, and reopen it, my session expires and make me to log in again. Can you please tell me that even if we set age of cookie, why the session get expires. I should allow me to remain loged in.
- Nakul
Very helpful article. It really cleared my basic idea about sessions and cookies. I am having really hard time understanding login process using Facebook API specially access token mechanism and logout process. After reading this tutorial, I am sure you will write a great tutorial explaining a simple(if it is!) login-logout process in a Java based web app using Facebook API. Thank you for this tutorial.
- Murtuza
Hi Pankaj, Thanks for ur tutorial, but i am facing some problem when i am navigating from one server to another in case of URL rewriting(cookie disabled). For eg, when coming back to shopping site after making payment at bank site the initial session id is not retained. It’s showing different session id. Could u please help me. Thanks in advance Aishwarya Singh, pune
- Aishwarya Singh
Thanks for the tutorial. It gives a very good understanding and idea of all the various concepts. It always helps me prep for my interviews. Thanks again and continue posting and sharing the knowledge.
- Anonym
Hi Pankaj, With the existing session management we also have to make the Cookie Secure using setSecure() and Httponly flag.
- HIMANSU NAYAK
can you post source code of this tutorial again. i cant get link download above. thanks
- tinhvh55
Hi! Great tutorial! When i’ve logged in, log out and then goes to the home-page, i get a nullPointerException. Do you know what might be the problem?
- Robin
Hi, I am testing with your code posted above in tutorial it is understanding very clearly… but i am getting an 404 error in webpage. (Servlet 3.0 Annotations) “message /SessionMgCooki/LoginServlet description The requested resource (/SessionMgCooki/LoginServlet) is not available.” This is my problem… Thanks.
- Prabhu.g
URI is not right, check the configuration for correct URI.
- Pankaj
Ya sir. I have check the URI. but the same 404 response from server.
- Prabhu.g
Pankaj Sir, as per above example n article its very knowledgeable i want use with database can u help me for above example how to use with database it my pleasure to if u guide me… thnks in advance…
- Jiral Dekhtawala
Sir, I have read the tutorial and i want to thnakyou for writing this tutorial.It is really helpful. I have a question to ask that how can i disable the back button after the logout button is clicked. As for now when i click the back button in the browser then it goes to the LoginSuccess page which we dont want. So, how can i prevent that. Thanks in advance.
- Saurabh
When you click back button, browser uses the cache to load the page. So there is nothing we can do from server side, however we can add javascript code to detect back button usage and forward to login page.
- Pankaj
Hi sir,iam having small doubt related to SessionManagement and Servlet Listeners.Question is whenever User is Directly Closing the Browser Window,how do we made session.invalidate() or some changes in database side,how to do sir?please help me Sir.
- Venkata Sriram
When user is closing window, you can’t do anything at server side. However we use cookies for session tracking and if you set the cookie to expire as soon as browser is closed, it will invalidate automatically.
- Pankaj
Hi sir thanks for reply but iam not using cookies explicitly for session handling sir.by using servletListener Events (HttpSessionEvent) also we cant perform any updation of status or something in database level sir.Correct me if iam wrong.Thanks Venkata Sriram
- Venkata Sriram
Hi pankaj, Thanks a lot. It works…!!.. :-) :-) continue your work…!!
- Rebecca
i have one doubt,how much data can store in session and cookies exactly can u tel me briefly
- rahul
It all depends on the memory for session data, you should keep it small to avoid memory issues. You can have many cookies but its value size is limited. Also it will add network overhead because it will be sent from both sides in every request and response, so you should keep it small.
- Pankaj
sir muze ek system pe kitne log har din me browser pe something search karte hai unka count banana hai to plz give me any suggestions.
- tushar
I have downloaded your files and tried to run the program in eclipse but whenever I submit the form from the login.html, I got this error: HTTP Status 404 - /practice/LogoutServlet. I have checked that I have all of your files (jsp, html, web, and java) locate in the same folder as yours but it still gives me this error. Please help me.
- Derek Nguyen
This examples looks good, but non of your examples work, after I login using admin and password I got a 404 error and import javax.servlet.annotation.WebServlet; and @WebServlet(“/LoginServlet”) give me an error, I try deleting them, I downloaded your examples, and import it in eclipse, I also copied and pasted them, I typed them and the same error 404. I like the definitions and the concepts use, but the example does not work.
- JS
Is your servlet container supports Servlet Spec 3? If not you will get these errors, try using Tomcat 7. Also check server logs for exact issue.
- Pankaj
Thanks for the article “If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.” i didnt understand this, please elloborate
- micheal
Hi I was trying Httpsession example but while running it Im getting value as null.Please help
- farah
Hi Sir, i want to remove .jsp extension from url in my java web application. I tried servlet mapping tag in web.xml file and i also tried to define my jsp file as servlet in web.xml file but its not working… so please give me some solution… thanks in advance…
- Sultan Khan
Start learning struts… u can do this and many more thing very easily…
- Amit
i am working on a web application project…the problem is that when i deploy then it runs good…the problem is that when i enter my inside page which must open after login but they open…so what can i do for this???
- Roopam
thank you so much sir
- rajeswari
Thanks… it’s nice
- Chetana
thanks sir … for session tutorial ,…
- amit
Hi, I m new to session management. I have a couple of questions. 1) In Session Management with HttpSession topic above, user name is set on both cookie and session. I don’t understand why do we have to set in both. Why cant we use only session object? 2) How to maintain the same session for multiple http requests? for example, on page refresh i need to access the value in the previously created session.
- Saravanan
Session Management with HttpSession LoginServlet.java Line number 33 session.setAttribute(“user”, “Pankaj”); can someone explain why use name pankaj in setAttribute
- zoyeb
Good one
- Ashok Korlakunta
Hi Sir… After logout, I m able to back page. But I want when we press back button it redirect to login page not back to loginsuccess page after logout.
- sud
Here is below what i am doing while(rs.next()){ LoadQueueProperties prop = new LoadQueueProperties(); prop.setGuid(rs.getString(“guid”)); prop.setHost_name(rs.getString(“host_name”)); prop.setColl_name(rs.getString(“collection_name”)); prop.setStage_id(rs.getInt(“stage_id”)); prop.setClient_name(rs.getString(“client_name”)); prop.setStatus_code(rs.getInt(“status_code”)); list.add(prop); } HttpSession session = request.getSession(); session.setAttribute(“loadQueueList”, list); response.sendRedirect(“LoadQueue.jsp”); in the jsp i am donig as below ${list.guid} ${list.host_name} ${list.coll_name} ${list.stage_id} but loadQueueList is coming as empty Any solution?
- swapnajit
Hatts Off…!
- puff
Really very good explanation with good example. Can you please tell me, By default which approach is used to maintain session by a web server like Apache tomcat?
- Ankit
Good tutorial Sir, looking forward for the future posts.
- shams
You sir, are the real MVP. Thank you so much, amazing tutorial!
- Luis Delgado