In this section we will discuss how can we manage the informations of a session in servlet.
Session Information
In this section we will discuss how can we manage the informations of a session in servlet.
A session has the various informations which we have need to manage them like is the session new or old, session id, access time etc. In the example given below I have tried to show you the information of session like session Id and count the number of time page invoked.
Exmaple :
SessionInfo
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionInfo extends HttpServlet {
static final String key = "SessionInfo.count";
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
HttpSession ssn = req.getSession(true);
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
HttpSession session = req.getSession(true);
int count = 1;
Integer i = (Integer) session.getAttribute(key);
if (i != null) {
count = i.intValue() + 1;
}
session.setAttribute(key, new Integer(count));
pw.println("Your session ID is " + ssn.getId());
pw.println("<br> and you have hit this page " + count
+ " time(s)during this session");
pw.println("<form method=GET action=\"" + req.getRequestURI() + "\">");
pw.println("<input type=submit " + "value=\"Refresh\">");
pw.println("</form>");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>SessionInfo</servlet-name> <servlet-class>SessionInfo</servlet-class> </servlet> <servlet-mapping> <servlet-name>SessionInfo</servlet-name> <url-pattern>/SessionInfo</url-pattern> </servlet-mapping> </web-app>
Output :
When you will execute the above example you will find the following output :


[ 0 ] Comments