Thursday 4 September 2014

isRequestedSessionIdFromURL() : Checks session ID came in as part of the request URL.

public boolean isRequestedSessionIdFromURL()
Checks whether the requested session ID came in as part of the request URL. Return true if the session ID came in as part of a URL; otherwise, false.

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()+"<br />");
            out.println("Is session comes as part of URL :" + req.isRequestedSessionIdFromURL());
            out.println("</h1></body></html>");
        }
    }   
}

Output



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment