Servlet HttpSession
HttpSession is an interface used by servlet container to create a session between Http client and Http server. So using this interface we can maintain the state of a user.
The object of HttpSession stores various information about the user. This interface is present in javax.servlet.http package.
Methods of HttpSession
These are some important methods provided by HttpSession interface.
Methods |
Description |
String getId() |
This method returns a unique id of client used to identify it. |
long getLastAccessedTime() |
This method provides the time when last request is made. It returns the time in milliseconds. |
Long getCreationTime() |
This method provides the time when first request is made. It returns the time in milliseconds. |
void setMaxInactiveInterval() |
This method sets time in seconds after which the session becomes invalid. |
Object getAttribute(String name) |
This method provides the value of attribute bind with the name passed within it. |
Example of HttpSession
In this example, we will maintain the state of a particular client. When a client makes first request then its unique id is generated. With each request, number of visit of a user is incremented by one unless request will be made within a specific period of time given in setMaxInactiveInterval() method unless the session becomes expire.
HttpSessionExample.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import javax.servlet.annotation.WebServlet; @WebServlet("/HttpSessionExample") public class HttpSessionExample extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); HttpSession session = req.getSession(); res.setContentType("text/html"); PrintWriter pw=res.getWriter(); Integer attribute=(Integer)session.getAttribute("attribute"); if (attribute == null) { attribute = new Integer(1); pw.println("<h1><center>NewUser</center></h1>"); } else { pw.println("<h1><center>Welcome back</center></h1>"); attribute = new Integer(attribute.intValue() + 1); } session.setAttribute("attribute",attribute); session.setMaxInactiveInterval(60); pw.println("<h2>Session id:"+session.getId()+"</h2>"); pw.println("<h2>Servlet last accessed time:"+new Date(session.getLastAccessedTime())+"</h2>"); pw.println("<h2>Number of time visit:"+attribute+"</h2>"); }}Output: