Monday, April 29, 2013

2.1.2 Sessions and Servlets

Purpose of using session is the same as of using cookies. The primary difference is, cookies are stored in client browser where sessions are stored in the server.



Sessions can be managed in four methods
  • Cookies
  • URL rewriting
  • Hidden form fields
  • SSL

Examples of these method would come later. For now, we shall use the servlet api to operate on a very simple session.


@WebServlet(name = "SessionServlet", urlPatterns = "/sessionTest")
public class SessionServlet extends HttpServlet {
    int counter = 0;
       public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out = response.getWriter();
           HttpSession mySession = request.getSession(true);

           synchronized (this){
               out.println(mySession.getId());
               out.println("
You have visited this page "+(++counter));
               out.println((counter == 1) ? "time":"times");
               if(counter % 5  == 0) mySession.invalidate();
           }

           out.close();
    }

}
In this code snippet, the retrieved which was associated with the request object. The boolean true means that a new session would be created if there is none in existence.

No comments:

Post a Comment