Java Servlet Session Management.
Servlets handling Session
- Without session management, each time a client makes a request to a server, it’s a brand new user with a brand new request from the server’s point of view.
- A session refers to the entire interaction between a client and a server from the time of the client’s first request, which generally begins the session, to the time the session is terminated.
- The session could be terminated by the client’s request, or the server could automatically close it after a certain period of time.
Creating and Using Sessions management in servlets
- You will get the session from the HttpServletResponse interface.
-
Here is some session related methods from the HttpServletRequest interface:
Method Description public HttpSession getSession() Will cause one session to be created. public HttpSession getSession(boolean) true = will cause one to be created;
false = will return null (no session)public String getRequestedSessionId() Gets the ID assigned by the server to the session public Boolean isRequestedSessionIdValid() Returns true if the request contains a valid session ID public Boolean isRequestedSessionIdFromCookie() Returns true if the session ID was sent as part of a cookie public Boolean isRequestedSessionIdFromURL() Returns true if the session ID was sent through URL rewriting - Default technique for session tracking is to use cookies.
- Cookies are sent in the header part of an HTTP message, so they must be set in the response prior to writing any data to the response.
Session Tracking with URL Rewriting in servlets
- Some users don’t like cookies and we need to use URL Rewriting.
-
HttpServletResponse interface:
Method Description public String encodeURL(String) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. public String encodeRedirectURL(String) Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. - Session is Useful for persisting information about a client and a client’s interactions with an application.
-
HttpSession interface:
Method (Get & Set types) Description public Object getAttribute(String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name. public Enumeration getAttributeNames() Returns an Enumeration of String objects containing the names of all the objects bound to this session. public void setAttribute(String name, Object value) Binds an object to this session, using the name specified. public void removeAttribute(String name) Removes the object bound with the specified name from this session.
Method (lifecycle types) Description public long getCreationTime() Returns the time when this session was created. public String getId() Returns a string containing the unique identifier assigned to this session. public long getLastAccessedTime() Returns the last time the client sent a request associated with this session. public boolean isNew() Returns true if the client does not yet know about the session or if the client chooses not to join the session. public void setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. public int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. public void invalidate() Invalidates this session then unbinds any objects bound to it.
Example of Servlet handling session.
As selected we use Netbeans IDE and Glassfish Server.
You can download this example here (needed tools can be found in the right menu on this page).
If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletSession).
-
Servlet handling session example:
package web; import javax.servlet.http.*; import java.io.*; public class LoginSES extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); String password = request.getParameter("password"); // Get the session - if no session exists create one HttpSession session = request.getSession(true); // Set some attribute values to the session // In this case user and password from the request and client session.setAttribute("username", username); session.setAttribute("password", password); try { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><body>"); writer.println("Thank you, " + username + ". You are now logged into the system"); // Encodes the specified URL by including the session ID in it, // or, if encoding is not needed, returns the URL unchanged String newURL = response.encodeURL("/ServletSession/GetSession"); // Return a <a> tag with the new url writer.println("Click <a href=\"" + newURL + "\">here</a> for another servlet"); writer.println("</body></html>"); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is LoginSES).
The html startup file, login.html, for the browser can be like this:<!DOCTYPE HTML> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> Please enter your username and password <form action="/ServletSession/LoginSES" method="POST"> <p><input type="text" name="username" style="width: 100px;" ></p> <p><input type="password" name="password" style="width: 100px;"></p> <p><input type="submit" value="Submit"></p> </form> </body> </html>
For those who participate in the review: create a HTML page in Netbeans and replace generated code for the html file with that shown above (the name of the html should be login and places in the folder web).
-
We need another servlet, GetSession, to see that we still have the session data.
Here is source code for the GetSession servlet:
package web; import javax.servlet.http.*; import java.io.*; import java.util.*; public class GetSession extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { // gets the session if it exists HttpSession session = request.getSession(false); try { response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html><body>"); // If you are not in a session - you are not logged in if (session == null) { writer.println("<p>You are not logged in</p>"); } else { writer.println("Thank you, you are already logged in"); writer.println("Here is the data in your session"); Enumeration names = session.getAttributeNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object value = session.getAttribute(name); writer.println("<p>name=" + name + " value=" + value + "</p>"); } } // Write html for a new login writer.println("<p><a href=\"/ServletSession/login.html\">Return" + "</a> to login page</p>"); writer.println("</body></html>"); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is GetSession).
Creating Deployment descriptor.
- To run this Servlet you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
-
The instructions are mainly defined to be deployment descriptors.
The standard part of the deployment descriptor should be in an
XML-file with the name web.xml. In the later version of java it is
possible to specify this in the form of annotations in front of the Servlet.
You may need to create a Deployment descriptor file, web.xml in Netbeans.
-
The contents of the web.xml file regarding servlet, LoginSES and GetSession,
should look like this:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <servlet> <servlet-name>LoginSES</servlet-name> <servlet-class>web.LoginSES</servlet-class> </servlet> <servlet> <servlet-name>GetSession</servlet-name> <servlet-class>web.GetSession</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginSES</servlet-name> <url-pattern>/LoginSES</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>GetSession</servlet-name> <url-pattern>/GetSession</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config>
- This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a Servlet.
- With a servlet tag we give the Servlet class a servlet name, which is used in the servlet-mapping tag to specify a url for the Servlet.
- In this way we can have many urls for the same servlet.
- As shown above, we also need to enter the GetSession with mapping information.
- If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
- The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file login.html. Reorganize the welcome-file-list to what is shown above.
Creating Web-server Deployment descriptor.
-
The context-root (in example /ServletSession) for the application
will in most cases be specified by a server vendor deployment descriptor.
For those who participate in the review: create a deployment descriptor in Netbeans.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd"> <sun-web-app error-url=""> <context-root>/ServletSession</context-root> <class-loader delegate="true"/> <jsp-config> <property name="keepgenerated" value="true"> <description> Keep a copy of the generated servlet class' java code. </description> </property> </jsp-config> </sun-web-app>
Run the application.
- For those who participate in the review: right click the Web-project and select Run.
- This results in that the application will be deployed to the server and started.
Login
Please enter your username and passwordEnter username, password and press the submit button.
name=password value=abcde
name=username value=admin
Return to login page