Thursday, 4 September 2014

isRequestedSessionIdFromCookie() : Checks whether given session comes as cookie

public boolean isRequestedSessionIdFromCookie()
Checks whether the requested session ID came in as a cookie.

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns = {"/DisplaySession"})
public class DisplaySession extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{
        try(PrintWriter out = res.getWriter()){
            StringBuilder msg = new StringBuilder();
            HttpSession mySession = req.getSession();
            Integer accessCount = (Integer)mySession.getAttribute("count");
            if(accessCount == null){
               msg.append("Welcome");
               mySession.setAttribute("count", 0);
               accessCount = 0;
            }
            else{
                accessCount = accessCount + 1;
                mySession.setAttribute("count", accessCount);
                msg.append("Welcome Back");
            }
            
            String sessionId = mySession.getId();
            long createdTime = mySession.getCreationTime();
            long lastAccessedTime = mySession.getLastAccessedTime();
            
            out.println("<html><head><title>Your Session Data</title></head>");
            out.println("<body><h1>" + msg);
            out.println("Your visit count " + accessCount +"<br />");
            out.println("Session Id :" + sessionId +"<br />");
            out.println("Created Time :" + createdTime +"<br />");
            out.println("Last Accessed Time :" + lastAccessedTime +"<br />");
            out.println("Is session comes as cookie :" + req.isRequestedSessionIdFromCookie());
            out.println("</h1></body></html>");
        }
    }   
}

Output

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment