Home
JAVA SERVLET
Applying Session into Basic Use
Here is an sample code using session tracking mechanism
import javax.servlet.*; import javax.servlet.http.*; /** * This is a simple servlet that uses session tracking and * to count the number of times a client session has * accessed this servlet. */ public class sesionprac extends HttpServlet { //Define our counter key into the session static final String COUNTER_KEY = "Counter.count"; /** *Performs the HTTP GET operation * * @param req The request from the client * @param resp The response from the servlet */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { //Get the session object for this client session. //The parameter indicates to create a session //object if one does not exist HttpSession session = req.getSession(true); //Set the content type of the response resp.setContentType("text/html"); //Get the PrintWriter to write the response java.io.PrintWriter out = resp.getWriter(); //Is there a count yet? int count = 1; Integer i = (Integer) session.getValue(COUNTER_KEY); //If a previous count exists, set is if (i != null) { count = i.intValue() + 1; } // Put the count back into the session session.putValue(COUNTER_KEY, new Integer (count)); // Print a standard header out.println("<html"); out.println("<head>"); out.println("<title>Session Counter</title>"); out.println("</head>"); out.println("<body>"); out.println("Your session ID is <b>" + count + "</b> times(s) during this browser session"); out.println("<form method=GET action=\"" + req.getRequestURI() + "\">"); out.println("<input type=submit " + "value=\"Hit page agaon\">"); out.println("</form>"); // Wrap up out.println("</body>"); out.println("</html>"); out.flush(); } }
Previous
Next