The idea is simple: on the client’s first request, the Container generates a unique session ID and gives it back to the client with the response. The client sends back the session ID with each subsequent request. The Container sees the ID, finds the matching session, and associates the session with the request. Somehow, the Container has to get the session ID to the client as part of the response, and the client has to send back the session ID as part of the request. The simplest and most common way to exchange the info is through cookies.
Below code is to know whether the session already existed or was just created.
HttpSession session = request.getSession();
if (session.isNew()) {
out.println(“This is a new session.”);
} else {
out.println(“Welcome back!”);
}
Checking whether the session is pre-existing one
HttpSession session = request.getSession(false);
if (session==null) {
out.println(“no session was available”);
out.println(“making one...”);
session = request.getSession();
} else {
out.println(“there was a session!”);
}
URL Rewriting:
If you use the session code—calling getSession() on the request—the Container tries to use cookies. If cookies aren’t enabled, it means the client will never join the session. In other words, the session’s isNew() method will always return true. In order to avoid this scenario we can use URL Rewriting
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String id=session.getId();
out.println("< html >< body >");
out.println("< a href=\"" + response.encodeURL("Form.html")+" topic="+id +"\" >click me< /a >");
out.println("< /body >< /html >");
Note :-URL rewriting works with sendRedirect() is given below
response. encodeRedirectURL(“/output.jsp”);
Three ways a session can die:
- It times out
- You call invalidate() on the session object
- The application goes down (crashes or is undeployed)
< web-app ... >
< servlet >
< /servlet >
< session-config >
< session-timeout >15< /session-timeout >
< /session-config >
< /web-app>
Setting session timeout for a specific session
session.setMaxInactiveInterval(20*60) where arg in seconds
No comments:
Post a Comment