A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession(), the user is given a unique ID to identify his session.
The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session.
setAttribute(String name, Object value): Binds an object to this session, using the name specified.
setMaxInactiveInterval(int interval): Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
getAttribute(String name): Returns the object bound with the specified name in this session, or null if no object is bound under the name.
getAttributeNames(): Returns an Enumeration of String objects containing the names of all the objects bound to this session.
getId(): Returns a string containing the unique identifier assigned to this session.
invalidate(): Invalidates this session then unbinds any objects bound to it.
removeAttribute(String name): Removes the object bound with the specified name from this session.
session Demo
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
// Create a session object.
HttpSession session = request.getSession(true);
session.setAttribute("uname",name);
//creating submit button
out.print("
");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("uname");
out.print("Hello!.. Welcome "+name);
out.close();
}catch(Exception e){
System.out.println(e);
}
}
}
set
SetSessionServlet
set
/servlet1
get
GetSessionServlet
get
/servlet2