Java Servlets Session

The software you need for the tutorials or the examples.

  1. Install the J2SE Development Kit.
  2. Install Netbeans IDE tool with Glassfish 3.0.1 server.
  3. Change the Glassfish 3.0.1 server HTTP listener ports.
  • All source code examples in this session is part of a complete example, ServletSession, that you can download.

What about Servlets and Session handling?

  • 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?

  • 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?

  • 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.
    A simple Servlet Session program:
    
    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();
        }
      }
    }
    
    How to try examples.
  • The client input form in this example is:
        Please enter your username and password
        <form action="/ServletSession/Login" method="POST">
          <p><input type="text" name="username" length="40">
          <p><input type="password" name="password" length="40">
          <p><input type="submit" value="Submit">
        </form>
        
    The form will look like:

  • When the user press the submit button he get a response like: "Thank you, Windy. You are now logged into the system Click here for another servlet"
  • If you click the here link you will access another servlet, GetSession.
    Here is source code for the GetSession servlet:
    
    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();
        }
      }
    }
    
    How to try examples.
  • All source code examples in this session is part of a complete example, ServletSession, that you can download.

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.