Set Session Expire Time in Servlets

Here is a very simple method that sets the session expire time in servlets.

Description

The following servlet application takes 2 numbers which it will add. This contains two servlets called MyServlet and AddServlet. The MyServlet class is intended to take the input parameters from HTML page and then check whether they are numbers or not. When they are numbers, those numbers are set as session attributes and a link to the /add url is shown. This url corresponds to the AddServlet class.
The AddServlet class takes these session attributes set in the MyServlet and converts them to int and prints their sum.
When creating session in MyServlet that session is set an expiry time after which it will expire. When the session is expired that session object no longer exists which means that the attributes set to it will no longer exist. Here it the expiry time is set to 5 seconds.

The method used to set an attribute to a session is setAttribute(String key, Object value)
The method used to get an attribute value from a session is getAttribute(String key). When you pass a key to this method that doesn't exist, it will return null.

Folder structure


ses1
│   index.html

└───WEB-INF
    │   web.xml
    │
    └───classes
            AddServlet.class
            AddServlet.java
            MyServlet.class
            MyServlet.java

index.html

<html>
    <body>
        <center>
            <form action="./first" method="post">
                <table>
                    <tr>
                        <td>Enter first number</td>
                        <td><input type="text" name="t1"/><br/></td>
                    </tr>

                    <tr>
                        <td>Enter second number</td>
                        <td><input type="text" name="t2"/><br/></td>
                    </tr>

                    <tr>
                        <td><input type="submit" value="add"/></td>
                        <td><input type="reset" value="clear"/></td>
                    </tr>
                </table>
            </form>
        </center>
    </body>
</html>

web.xml (deployment descriptor)

<web-app>
    <servlet>
        <servlet-name>firstser</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>firstser</servlet-name>
        <url-pattern>/first</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>finalser</servlet-name>
        <servlet-class>AddServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>finalser</servlet-name>
        <url-pattern>/add</url-pattern>
    </servlet-mapping>   
</web-app>

MyServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class MyServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        PrintWriter pw=res.getWriter();

        // create session object or get existing session object (if any)
        HttpSession ses=req.getSession();

        // set 5 seconds
        // default is 1800 seconds (30 minutes)
        ses.setMaxInactiveInterval(5);

        String num1=req.getParameter("t1");
        String num2=req.getParameter("t2");

        try
        {
        int x=Integer.parseInt(num1);
        int y=Integer.parseInt(num2);

        ses.setAttribute("fno",num1);
        ses.setAttribute("sno",num2);

        pw.println("<html>");
        pw.println("<body>");
        pw.println("Add before "+ses.getMaxInactiveInterval()+" seconds.. Quick\n");
        pw.println("<a href='./add'>Click here to add</a>");
        pw.println("</body>");
        pw.println("</html>");
        }catch(Exception e){
            pw.println("Enter valid input");
        }

        pw.close();
    }
}

AddServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class AddServlet extends HttpServlet
{
    // doGet because AddServlet is called via anchor tag <a href='./add'>Click here to add</a>
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        PrintWriter pw=res.getWriter();

        // create session object or get existing session object (if any)

        // when session expires i.e. if the user doesn't click on the link
        // within 5 seconds then new session is created and its object is returned
        // When this happens, the new session object will contain no attributes
        // i.e. no fno, no sno
        HttpSession ses=req.getSession();

        // Get attributes from session created in MyServlet
        try
        {

        // here both number1 and number2 will be null if session
        // expires
        String number1=(String)ses.getAttribute("fno");
        String number2=(String)ses.getAttribute("sno");

        // You get a NumberFormatException when session expires
        // because you cannot parse null to int
        int x=Integer.parseInt(number1);
        int y=Integer.parseInt(number2);

        pw.println("The sum is "+(x+y));
        }catch(NumberFormatException e)
        {
            pw.println("Session expired");
        }

        // print when the session was created
        // getCreationDate() returns long (milliseconds) from Jan 1 1970, 00:00:00
        // to current date, this is passed to Date constructor for a viewable format
        pw.println("The session was created on "+new Date(ses.getCreationTime()));

        // when was session last accessed i.e. last getSession() call
        pw.println("The session was last accessed on "+new Date(ses.getLastAccessedTime()));

        pw.close();
    }
}


Posted by at on

Tags: Servlets,