Thursday 4 September 2014

isRequestedSessionIdValid() : Checks whether the requested session ID is still valid.

public boolean isRequestedSessionIdValid()
Checks whether the requested session ID is still valid. If the client did not specify any session ID, this method returns 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() +"<br />");
            out.println("Is session is still valid :" + req.isRequestedSessionIdValid()+"<br />");
            out.println("</h1></body></html>");
        }
    }   
}

Output


Refresh the window.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment