Thursday, 4 September 2014

changeSessionId() : Change Session Id

HttpServletRequest class provides a method 'changeSessionId()' with this you can change the session.
String changeSessionId()
Change the session id of the current session associated with this request and return the new session id.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@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");
            }
            req.changeSessionId();
            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("</h1></body></html>");
        }
    }   
}

Refresh the page, then you can see the result.






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment