banner



Does Java Http Session Store Data In The Server??

Session Management in Java Servlet Web Applications is a very interesting topic. Session in Java Servlet are managed through unlike ways, such as Cookies, HttpSession API, URL rewriting etc.

Session Management in Java, Session in Java Servlet using Cookies, HttpServlet, URL Rewriting

This is the third article in the serial of Web Applications tutorial in Java, you lot might want to cheque out earlier ii articles also.

  1. Java Web Awarding Tutorial
  2. Coffee Servlet Tutorial

Session Management in Coffee

This article is aimed to explain about session direction in servlets using different techniques and with example programs.

  1. What is a Session?
  2. Session Direction in Java – Cookies
  3. Session in Coffee Servlet – HttpSession
  4. Session Management in Java Servlet – URL Rewriting
  1. What is a Session?

    HTTP protocol and Web Servers are stateless, what information technology means is that for web server every request is a new request to process and they tin can't identify if it's coming from client that has been sending request previously.

    But sometimes in spider web applications, nosotros should know who the customer is and procedure the asking appropriately. 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 tin can accuse the amount to correct client.

    Session is a conversional state between client and server and it tin can consists of multiple request and response between client and server. Since HTTP and Spider web Server both are stateless, the just mode to maintain a session is when some unique information about the session (session id) is passed between server and customer in every request and response.

    There are several ways through which we can provide unique identifier in asking and response.

    1. User Authentication – This is the very common way where we user can provide authentication credentials from the login folio and then we tin laissez passer the hallmark data between server and client to maintain the session. This is not very constructive method because information technology wont work if the aforementioned user is logged in from different browsers.
    2. HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts navigating, nosotros can set its value unique to the user and keep runway of the session. This method can't exist used with links because information technology needs the grade to be submitted every time request is made from client to server with the subconscious field. Also information technology's non secure considering we can go the hidden field value from the HTML source and utilise it to hack the session.
    3. URL Rewriting – We tin can append a session identifier parameter with every asking and response to keep rail of the session. This is very slow because we need to keep track of this parameter in every response and brand certain it'due south not clashing with other parameters.
    4. 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 asking header and nosotros can use information technology to keep track of the session. We can maintain a session with cookies but if the customer disables the cookies, so it won't work.
    5. Session Management API – Session Management API is built on height of above methods for session tracking. Some of the major disadvantages of all the above methods are:
      • Virtually of the time we don't want to simply runway the session, we have to shop some data into the session that nosotros tin can utilise in future requests. This will crave a lot of try if we try to implement this.
      • All the above methods are not complete in themselves, all of them won't work in a particular scenario. So we demand a solution that can utilize these methods of session tracking to provide session management in all cases.

      That'due south why we need Session Management API and J2EE Servlet engineering science comes with session management API that we can apply.

  2. Session Management in Coffee – Cookies

    Cookies are used a lot in web applications to personalize response based on your choice or to keep track of session. Earlier moving forward to the Servlet Session Direction API, I would similar to show how tin we keep track of session with cookies through a small web application.

    We will create a dynamic web application ServletCookieExample with projection structure like below image.

    Session in Java using Cookies

    Deployment descriptor web.xml of the web application is:

                                              <?xml version="one.0" encoding="UTF-8"?> <spider 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="three.0">   <display-proper name>ServletCookieExample</brandish-proper 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</championship> </head> <body>  <form action="LoginServlet" method="post">  Username: <input type="text" name="user"> <br> Password: <input type="countersign" proper noun="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 coffee.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 form LoginServlet  */ @WebServlet("/LoginServlet") public course LoginServlet extends HttpServlet { 	private static final long serialVersionUID = 1L; 	private final String userID = "Pankaj"; 	private final Cord password = "journaldev";  	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException {  		// become request parameters for userID and password 		String user = request.getParameter("user"); 		Cord pwd = asking.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 proper noun or password is wrong.</font>"); 			rd.include(request, response); 		}  	}  }                                      

    Notice the cookie that nosotros are setting to the response then forwarding it to LoginSuccess.jsp, this cookie will be used there to rails 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 whatsoever other request.

                                              <%@ page language="java" contentType="text/html; charset=Usa-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 !=naught){ for(Cookie cookie : cookies){ 	if(cookie.getName().equals("user")) userName = cookie.getValue(); } } if(userName == cipher) response.sendRedirect("login.html"); %> <h3>Hi <%=userName %>, Login successful.</h3> <br> <form action="LogoutServlet" method="post"> <input blazon="submit" value="Logout" > </form> </trunk> </html>                                      

    Observe that if nosotros try to access the JSP directly, it will forward us to the login page. When nosotros volition click on Logout push button, nosotros should make sure that cookie is removed from client browser.

                                              packet 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 course 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;     			interruption;     		}     	}     	}     	if(loginCookie != aught){     		loginCookie.setMaxAge(0);         	response.addCookie(loginCookie);     	}     	response.sendRedirect("login.html");     }  }                                      

    There is no method to remove the cookie but nosotros can prepare the maximum age to 0 then that information technology will be deleted from client browser immediately.

    When we run above awarding, we get response like below images.

    Session Management in Java using Cookies
    Java Servlet Session Management using Cookies

  3. Session in Java Servlet – HttpSession

    Servlet API provides Session management through HttpSession interface. We can become session from HttpServletRequest object using following methods. HttpSession allows us to set objects as attributes that can be retrieved in future requests.

    1. HttpSession getSession() – This method always returns a HttpSession object. It returns the session object attached with the asking, if the asking has no session attached, then it creates a new session and return information technology.
    2. HttpSession getSession(boolean flag) – This method returns HttpSession object if request has session else information technology returns aught.

    Some of the important methods of HttpSession are:

    1. String getId() – Returns a string containing the unique identifier assigned to this session.
    2. Object getAttribute(String proper name) – Returns the object bound with the specified proper noun in this session, or null if no object is leap under the name. Some other methods to work with Session attributes are getAttributeNames(), removeAttribute(Cord proper name) and setAttribute(String name, Object value).
    3. long getCreationTime() – Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. We can become concluding accessed fourth dimension with getLastAccessedTime() method.
    4. setMaxInactiveInterval(int interval) – Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. We can go session timeout value from getMaxInactiveInterval() method.
    5. ServletContext getServletContext() – Returns ServletContext object for the awarding.
    6. boolean isNew() – Returns true if the client does not all the same know about the session or if the client chooses non to join the session.
    7. void invalidate() – Invalidates this session and so unbinds whatever objects bound to it.

    Understanding JSESSIONID Cookie

    When we use HttpServletRequest getSession() method and it creates a new request, information technology creates the new HttpSession object and besides add a Cookie to the response object with name JSESSIONID and value as session id. This cookie is used to place the HttpSession object in further requests from client. If the cookies are disabled at customer 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 information technology for our application purposes to avoid any session related bug.

    Permit'southward see case of session management using HttpSession object. Nosotros will create a dynamic web project in Eclipse with servlet context as ServletHttpSessionExample. The project structure will look like below image.

    HttpSession servlet session management

    login.html is same like before example and defined as welcome page for the application in web.xml

    LoginServlet servlet will create the session and set attributes that nosotros can use in other resources or in hereafter 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.note.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 form LoginServlet  */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { 	private static last long serialVersionUID = 1L; 	private last String userID = "admin"; 	private last String password = "password";  	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException {  		// get request parameters for userID and countersign 		String user = asking.getParameter("user"); 		Cord pwd = asking.getParameter("pwd"); 		 		if(userID.equals(user) && password.equals(pwd)){ 			HttpSession session = asking.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 countersign is incorrect.</font>"); 			rd.include(asking, response); 		}  	}  }                                      

    Our LoginSuccess.jsp code is given beneath.

                                              <%@ 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> <% //permit admission only if session exists String user = null; if(session.getAttribute("user") == nix){ 	response.sendRedirect("login.html"); }else user = (Cord) session.getAttribute("user"); String userName = zero; String sessionID = null; Cookie[] cookies = asking.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>Hello <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3> <br> User=<%=user %> <br> <a href="CheckoutPage.jsp">Checkout Page</a> <course action="LogoutServlet" method="postal service"> <input type="submit" value="Logout" > </form> </trunk> </html>                                      

    When a JSP resource is used, container automatically creates a session for it, so we can't bank check if session is goose egg to brand 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.

                                              <%@ folio language="coffee" 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</championship> </caput> <body> <% //permit access only if session exists if(session.getAttribute("user") == naught){ 	response.sendRedirect("login.html"); } String userName = null; String sessionID = zippo; Cookie[] cookies = asking.getCookies(); if(cookies !=cipher){ for(Cookie cookie : cookies){ 	if(cookie.getName().equals("user")) userName = cookie.getValue(); } } %> <h3>Hello <%=userName %>, do the checkout.</h3> <br> <form action="LogoutServlet" method="mail service"> <input type="submit" value="Logout" > </class> </torso> </html>                                      

    Our LogoutServlet code is given below.

                                              bundle 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 != zilch){     	for(Cookie cookie : cookies){     		if(cookie.getName().equals("JSESSIONID")){     			Arrangement.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 != cypher){     		session.invalidate();     	}     	response.sendRedirect("login.html");     }  }                                      

    Notice that I am press JSESSIONID cookie value in logs, you can check server log where it will be printing the same value every bit Session Id in LoginSuccess.jsp

    Below images shows the execution of our spider web application.

    Session in Java Servlet web application

    HttpSession Session in Java Servlet web application

    Session in Java Servlet web application destroy

  4. Session Management in Java Servlet – URL Rewriting

    As we saw in last section that we tin can manage a session with HttpSession but if we disable the cookies in browser, it won't piece of work considering server will not receive the JSESSIONID cookie from client. Servlet API provides back up for URL rewriting that we can use to manage session in this instance.

    The best part is that from coding point of view, it'south very piece of cake to use and involves ane step – encoding the URL. Another good affair with Servlet URL Encoding is that it'south a fallback approach and it kicks in only if browser cookies are disabled.

    We tin can encode URL with HttpServletResponse encodeURL() method and if we have to redirect the request to another resource and we want to provide session data, we can use encodeRedirectURL() method.

    We will create a similar project like above except that nosotros will use URL rewriting methods to make certain session management works fine even if cookies are disabled in browser.

    ServletSessionURLRewriting project structure in eclipse looks like below image.

    Session in Java Servlet URL Rewriting

                                              package com.journaldev.servlet.session;  import java.io.IOException; import coffee.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 course LoginServlet extends HttpServlet { 	private static final long serialVersionUID = 1L; 	private final Cord userID = "admin"; 	private final Cord password = "password";  	protected void doPost(HttpServletRequest request, 			HttpServletResponse response) throws ServletException, IOException {  		// get request parameters for userID and password 		Cord user = request.getParameter("user"); 		String pwd = asking.getParameter("pwd"); 		 		if(userID.equals(user) && countersign.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 cord 			Cord 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); 		}  	}  }                                      
                                              <%@ folio linguistic communication="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=United states-ASCII"> <title>Login Success Page</title> </head> <body> <% //permit access only if session exists Cord user = null; if(session.getAttribute("user") == null){ 	response.sendRedirect("login.html"); }else user = (Cord) session.getAttribute("user"); String userName = naught; String sessionID = cipher; Cookie[] cookies = request.getCookies(); if(cookies !=naught){ 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>How-do-you-do <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3> <br> User=<%=user %> <br> <!-- need to encode all the URLs where nosotros want session information to be passed --> <a href="<%=response.encodeURL("CheckoutPage.jsp") %>">Checkout Page</a> <class action="<%=response.encodeURL("LogoutServlet") %>" method="postal service"> <input type="submit" value="Logout" > </class> </body> </html>                                      
                                              <%@ page language="coffee" contentType="text/html; charset=United states of america-ASCII"     pageEncoding="U.s.-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://world wide web.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=United states of america-ASCII"> <title>Login Success Page</title> </caput> <body> <% String userName = null; //allow admission only if session exists if(session.getAttribute("user") == null){ 	response.sendRedirect("login.html"); }else userName = (String) session.getAttribute("user"); String sessionID = null; Cookie[] cookies = asking.getCookies(); if(cookies !=null){ for(Cookie cookie : cookies){ 	if(cookie.getName().equals("user")) userName = cookie.getValue(); } } %> <h3>How-do-you-do <%=userName %>, do the checkout.</h3> <br> <course action="<%=response.encodeURL("LogoutServlet") %>" method="post"> <input type="submit" value="Logout" > </class> </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 course LogoutServlet extends HttpServlet { 	private static final long serialVersionUID = 1L;             protected void doPost(HttpServletRequest asking, 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);     	Arrangement.out.println("User="+session.getAttribute("user"));     	if(session != nix){     		session.invalidate();     	}     	//no encoding considering 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 accost bar. Also observe that on LoginSuccess page, user name is null because browser is non sending the cookie send in the last response.

    Session in Java URL Rewriting

    Session Management in Java URL Rewriting

    Session in Java URL Rewriting Logout

    If cookies are non disabled, you won't encounter 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 futurity articles.

Update: Cheque out next article in the series Servlet Filter.

Download Projects

[no_toc]

Does Java Http Session Store Data In The Server??,

Source: https://www.journaldev.com/1907/java-session-management-servlet-httpsession-url-rewriting

Posted by: stephensexameste1969.blogspot.com

0 Response to "Does Java Http Session Store Data In The Server??"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel