A Valid Part Ii and Iii Must Be Attached Please Correct and Try Again
Session Management in Java Servlet Web Applications is a very interesting topic. Session in Coffee 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.
- Java Web Application Tutorial
- Java Servlet Tutorial
Session Management in Java
This article is aimed to explain about session management in servlets using different techniques and with example programs.
- What is a Session?
- Session Management in Java – Cookies
- Session in Coffee Servlet – HttpSession
- Session Management in Java Servlet – URL Rewriting
-
What is a Session?
HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new asking to procedure and they can't place 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 procedure the request accordingly. For example, a shopping cart application should know who is sending the request to add together an item and in which cart the particular has to be added or who is sending checkout asking so that it can accuse the corporeality to correct client.
Session is a conversional land between client and server and it tin 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 well-nigh 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 asking and response.
- User Hallmark – This is the very common way where nosotros user tin can provide authentication credentials from the login folio and then we tin can pass the authentication information between server and client to maintain the session. This is not very constructive method because it wont work if the aforementioned user is logged in from unlike browsers.
- HTML Hidden Field – We tin can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and go along track of the session. This method can't be used with links because information technology needs the form to be submitted every time request is made from client to server with the hidden field. Too it'due south not secure considering we can get the hidden field value from the HTML source and use it to hack the session.
- URL Rewriting – We tin append a session identifier parameter with every request and response to keep track of the session. This is very tedious considering nosotros need to keep rails of this parameter in every response and make certain it's non clashing with other parameters.
- Cookies – Cookies are small piece of data 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 we can utilise information technology to keep track of the session. We tin can maintain a session with cookies but if the client disables the cookies, then it won't work.
- Session Direction API – Session Management API is built on superlative of above methods for session tracking. Some of the major disadvantages of all the to a higher place methods are:
- Most of the time we don't want to simply runway the session, we have to store some data into the session that we can use in future requests. This will require a lot of effort if nosotros attempt to implement this.
- All the above methods are not complete in themselves, all of them won't work in a particular scenario. And then we need a solution that can employ these methods of session tracking to provide session direction in all cases.
That'south why we need Session Direction API and J2EE Servlet engineering comes with session management API that we can utilise.
-
Session Management in Java – Cookies
Cookies are used a lot in web applications to personalize response based on your choice or to proceed track of session. Before moving frontward to the Servlet Session Management API, I would like to show how can we keep track of session with cookies through a modest spider web application.
We will create a dynamic web application ServletCookieExample with project structure like below paradigm.
Deployment descriptor spider web.xml of the web application is:
<?xml version="1.0" encoding="UTF-eight"?> <web-app xmlns:xsi="https://world wide web.w3.org/2001/XMLSchema-instance" xmlns="https://java.dominicus.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sunday.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <brandish-proper noun>ServletCookieExample</brandish-name> <welcome-file-listing> <welcome-file>login.html</welcome-file> </welcome-file-list> </web-app>Welcome folio of our application is login.html where we will become authentication details from user.
<!DOCTYPE html> <html> <caput> <meta charset="US-ASCII"> <title>Login Folio</title> </head> <trunk> <form action="LoginServlet" method="mail"> Username: <input type="text" proper name="user"> <br> Password: <input type="password" name="pwd"> <br> <input type="submit" value="Login"> </class> </torso> </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 class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { individual 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 { // get request parameters for userID and password String user = request.getParameter("user"); Cord 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=cerise>Either user name or password is wrong.</font>"); rd.include(request, response); } } }Notice the cookie that we are setting to the response and and then forwarding information technology to LoginSuccess.jsp, this cookie will be used there to track the session. Also notice that cookie timeout is set up to xxx minutes. Ideally at that place should be a complex logic to set the cookie value for session tracking and then that it won't collide with whatsoever other request.
<%@ folio language="java" contentType="text/html; charset=US-ASCII" pageEncoding="U.s.-ASCII"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML four.01 Transitional//EN" "https://world wide web.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Blazon" content="text/html; charset=US-ASCII"> <championship>Login Success Folio</championship> </head> <body> <% Cord 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>Howdy <%=userName %>, Login successful.</h3> <br> <class action="LogoutServlet" method="post"> <input type="submit" value="Logout" > </form> </torso> </html>Observe that if we effort to admission the JSP directly, information technology will forwards us to the login folio. When we will click on Logout button, we should make sure that cookie is removed from client browser.
package com.journaldev.servlet.session; import coffee.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 = asking.getCookies(); if(cookies != zippo){ for(Cookie cookie : cookies){ if(cookie.getName().equals("user")){ loginCookie = cookie; intermission; } } } if(loginCookie != zippo){ loginCookie.setMaxAge(0); response.addCookie(loginCookie); } response.sendRedirect("login.html"); } }There is no method to remove the cookie merely we can set up the maximum historic period to 0 then that it volition be deleted from client browser immediately.
When we run above application, we get response similar beneath images.
-
Session in Coffee Servlet – HttpSession
Servlet API provides Session management through
HttpSessioninterface. We can get session from HttpServletRequest object using following methods. HttpSession allows us to prepare objects as attributes that tin exist retrieved in hereafter requests.- HttpSession getSession() – This method always returns a HttpSession object. Information technology returns the session object attached with the asking, if the asking has no session fastened, and then it creates a new session and return it.
- HttpSession getSession(boolean flag) – This method returns HttpSession object if request has session else it returns null.
Some of the important methods of HttpSession are:
- String getId() – Returns a string containing the unique identifier assigned to this session.
- Object getAttribute(String proper noun) – Returns the object bound with the specified name in this session, or null if no object is bound under the proper noun. Some other methods to work with Session attributes are
getAttributeNames(),removeAttribute(String name)andsetAttribute(String name, Object value). - long getCreationTime() – Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. We can go final accessed time with
getLastAccessedTime()method. - setMaxInactiveInterval(int interval) – Specifies the fourth dimension, in seconds, betwixt customer requests before the servlet container volition invalidate this session. We tin can get session timeout value from
getMaxInactiveInterval()method. - ServletContext getServletContext() – Returns ServletContext object for the awarding.
- boolean isNew() – Returns truthful if the customer does not nonetheless know about the session or if the client chooses not to join the session.
- void invalidate() – Invalidates this session then unbinds whatsoever objects bound to information technology.
Understanding JSESSIONID Cookie
When we utilize HttpServletRequest getSession() method and it creates a new request, it creates the new HttpSession object and besides add together 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 customer. If the cookies are disabled at client side and we are using URL rewriting and so this method uses the jsessionid value from the request URL to observe the corresponding session. JSESSIONID cookie is used for session tracking, so we should not use it for our application purposes to avert any session related issues.
Allow's see example of session management using HttpSession object. We volition create a dynamic web project in Eclipse with servlet context equally ServletHttpSessionExample. The project structure will look similar beneath image.
login.html is aforementioned like earlier example and defined equally welcome folio for the application in web.xml
LoginServlet servlet will create the session and set up attributes that we can use in other resources or in future requests.
bundle 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; individual concluding String userID = "admin"; individual final String password = "password"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get asking parameters for userID and password String user = request.getParameter("user"); Cord 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*sixty); Cookie userName = new Cookie("user", user); userName.setMaxAge(xxx*lx); 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 beneath.
<%@ folio language="java" contentType="text/html; charset=US-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=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"); Cord userName = null; String sessionID = cipher; 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>Hello <%=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" > </class> </body> </html>When a JSP resource is used, container automatically creates a session for it, and so nosotros tin can't check if session is null to make sure if user has come through login folio, then we are using session attribute to validate asking.
CheckoutPage.jsp is another page and information technology's code is given below.
<%@ folio language="java" contentType="text/html; charset=US-ASCII" pageEncoding="United states of america-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=U.s.-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 = cipher; Cookie[] cookies = request.getCookies(); if(cookies !=zero){ for(Cookie cookie : cookies){ if(cookie.getName().equals("user")) userName = cookie.getValue(); } } %> <h3>Hi <%=userName %>, exercise the checkout.</h3> <br> <form action="LogoutServlet" method="post"> <input type="submit" value="Logout" > </form> </body> </html>Our LogoutServlet code is given below.
packet com.journaldev.servlet.session; import coffee.io.IOException; import javax.servlet.ServletException; import javax.servlet.notation.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 asking, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = asking.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID="+cookie.getValue()); pause; } } } //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, yous can check server log where it will be printing the aforementioned value as Session Id in LoginSuccess.jsp
Beneath images shows the execution of our spider web awarding.
-
Session Management in Java Servlet – URL Rewriting
Equally we saw in concluding section that we can manage a session with HttpSession but if we disable the cookies in browser, it won't work because server volition non receive the JSESSIONID cookie from client. Servlet API provides support for URL rewriting that we tin employ to manage session in this example.
The all-time office is that from coding point of view, it's very easy to use and involves ane step – encoding the URL. Another good thing with Servlet URL Encoding is that it'southward a fallback approach and it kicks in simply if browser cookies are disabled.
We can encode URL with HttpServletResponse
encodeURL()method and if we have to redirect the asking to another resource and we want to provide session data, we can useencodeRedirectURL()method.Nosotros will create a similar project like above except that nosotros will use URL rewriting methods to make certain session management works fine fifty-fifty if cookies are disabled in browser.
ServletSessionURLRewriting projection structure in eclipse looks similar 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 course LoginServlet */ @WebServlet("/LoginServlet") public form LoginServlet extends HttpServlet { private static last long serialVersionUID = 1L; individual final Cord userID = "admin"; private terminal Cord 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*sixty); Cookie userName = new Cookie("user", user); response.addCookie(userName); //Go the encoded URL cord 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(asking, response); } } }<%@ page language="java" contentType="text/html; charset=United states of america-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=Usa-ASCII"> <title>Login Success Page</championship> </head> <torso> <% //allow access only if session exists Cord user = zilch; if(session.getAttribute("user") == zippo){ response.sendRedirect("login.html"); }else user = (Cord) session.getAttribute("user"); Cord userName = null; Cord sessionID = cipher; 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>Hullo <%=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> <course activeness="<%=response.encodeURL("LogoutServlet") %>" method="postal service"> <input type="submit" value="Logout" > </form> </body> </html><%@ folio 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> <caput> <meta http-equiv="Content-Type" content="text/html; charset=United states of america-ASCII"> <championship>Login Success Page</championship> </caput> <torso> <% String userName = null; //allow access only if session exists if(session.getAttribute("user") == cypher){ response.sendRedirect("login.html"); }else userName = (Cord) 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 %>, practice the checkout.</h3> <br> <form activity="<%=response.encodeURL("LogoutServlet") %>" method="postal service"> <input blazon="submit" value="Logout" > </form> </trunk> </html>package com.journaldev.servlet.session; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.notation.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 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[] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ Organization.out.println("JSESSIONID="+cookie.getValue()); } cookie.setMaxAge(0); response.addCookie(cookie); } } //invalidate the session if exists HttpSession session = asking.getSession(false); System.out.println("User="+session.getAttribute("user")); if(session != nothing){ session.invalidate(); } //no encoding because we have invalidated the session response.sendRedirect("login.html"); } }When nosotros run this project keeping cookies disabled in the browser, below images shows the response pages, observe the jsessionid in URL of browser address bar. As well notice that on LoginSuccess page, user name is cypher because browser is not sending the cookie ship in the terminal response.
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, nosotros will look into Servlet Filters and Listeners and Cookies in future articles.
Update: Check out adjacent commodity in the series Servlet Filter.
Download Projects
[no_toc]
Source: https://www.journaldev.com/1907/java-session-management-servlet-httpsession-url-rewriting
0 Response to "A Valid Part Ii and Iii Must Be Attached Please Correct and Try Again"
Post a Comment