Saturday 7 April 2018

HttpSession with example in Servlet

HttpSession with example in Servlet,HttpSession ,request.getSession(),How to create a new session for http client,getSession(),getSession(true),How to get existing session for an http client,getSession(false),HttpServletResponse ,How to configure session timeout in deployment descriptor (web.xml),Methods of HttpSession,public void setAttribute(String name, Object value),public Object getAttribute(String name),public Enumeration getAttributeNames(),public void removeAttribute(String name),setMaxInactiveInterval(int interval),Example of using HttpSession,setAttribute(),

The HttpSession object is used for session management. 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. This unique ID can be stored into a cookie or in a request parameter.
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.

How to create a new session for http client

To create an HttpSession object if the user is visiting the web app for the first time or fetch the session if one already exists, use the methods getSession() or getSession(true) of the HttpServletRequest objecta shown below. 
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException  
 {  
    HttpSession session = req.getSession();  
 }  

 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
 throws ServletException, IOException  
 {  
    HttpSession session = req.getSession(true);  
 } 

How to get existing session for an http client

To get the HttpSession object if it already exists and return null otherwise, use the method getSession(false) of the HttpServletResponse object as shown in the example below. 
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  
 {  
    HttpSession session = req.getSession(false);  
 } 

How to configure session timeout in deployment descriptor (web.xml)

You can configure the timeout period of an idle session in the deployment descriptor (web.xml) as shown below. The example below configures the timeout as 30 minutes.
<web-app>  
    <session-config>  
        <session-timeout>30</session-timeout>  
    </session-config>  
</web-app> 
   

Methods of HttpSession

  • public void setAttribute(String name, Object value): Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, then this method replaces the existing attributes.
  • public Object getAttribute(String name): Returns the String object specified in the parameter, from the session object. If no object is found for the specified attribute, then the getAttribute() method returns null.
  • public Enumeration getAttributeNames(): Returns an Enumeration that contains the name of all the objects that are bound as attributes to the session object.
  • public void removeAttribute(String name): Removes the given attribute from session.
  • setMaxInactiveInterval(int interval): Sets the session inactivity time in seconds. This is the time in seconds that specifies how long a sessions remains active since last request received from client.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value from the session scope in another servlet. To set the attribute in the session scope, we have used the setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute method.

index.html
<form action="servlet1">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="go"/>  </form>  

Dashzin1.java

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
  
public class Dashzin1 extends HttpServlet {  
  
public void doGet(HttpServletRequest request, HttpServletResponse response){  
        try{  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        String n=request.getParameter("userName");  
        out.print("Welcome "+n);  
          
        HttpSession session=request.getSession();  
        session.setAttribute("uname",n);  
  
        out.print("<a href='servlet2'>visit</a>");  
                  
        out.close();  
  
                }catch(Exception e){System.out.println(e);}  
    }  
  
}

Dashzin2.java


import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class Dashzin2 extends HttpServlet {  
  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
        try{  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        HttpSession session=request.getSession(false);  
        String n=(String)session.getAttribute("uname");  
        out.print("Hello "+n);  
  
        out.close();  
  
                }catch(Exception e){System.out.println(e);}  
    }  
      
}  

web.xml


<web-app>  
  
<servlet>  
<servlet-name>s1</servlet-name>  
<servlet-class>Dashzin1</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>s1</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>  
  
<servlet>  
<servlet-name>s2</servlet-name>  
<servlet-class>Dashzin2 </servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>s2</servlet-name>  
<url-pattern>/servlet2</url-pattern>  
</servlet-mapping>  
  
</web-app>   









DashZin

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

0 comments:

Post a Comment