banner



How To Create Session Object In Java

TheHttpSession 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.

This is how you create a HttpSession object.

protected void doPost(HttpServletRequest req,     HttpServletResponse res)     throws ServletException, IOException {         HttpSession session = req.getSession(); }

You can store the user information into the session object by using setAttribute() method and later when needed this information can be fetched from the session. This is how you store info in session. Here we are storing username, emailid and userage in session with the attribute name uName, uemailId and uAge respectively.

session.setAttribute("uName", "ChaitanyaSingh"); session.setAttribute("uemailId", "[email protected]"); session.setAttribute("uAge", "30");

This First parameter is the attribute name and second is the attribute value. For e.g. uName is the attribute name and ChaitanyaSingh is the attribute value in the code above.

TO get the value from session we use the getAttribute() method of HttpSession interface. Here we are fetching the attribute values using attribute names.

String userName = (String) session.getAttribute("uName"); String userEmailId = (String) session.getAttribute("uemailId"); String userAge = (String) session.getAttribute("uAge");

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.

For the complete list of methods, refer the official documentation.

Session Example

index.html

<form action="login">   User Name:<input type="text" name="userName"/><br/>   Password:<input type="password" name="userPassword"/><br/>   <input type="submit" value="submit"/> </form>

MyServlet1.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet1 extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response){      try{       response.setContentType("text/html");       PrintWriter pwriter = response.getWriter();        String name = request.getParameter("userName");       String password = request.getParameter("userPassword");       pwriter.print("Hello "+name);       pwriter.print("Your Password is: "+password);       HttpSession session=request.getSession();       session.setAttribute("uname",name);       session.setAttribute("upass",password);       pwriter.print("<a href='welcome'>view details</a>");       pwriter.close();     }catch(Exception exp){        System.out.println(exp);      }   } }

MyServlet2.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet2 extends HttpServlet {   public void doGet(HttpServletRequest request, HttpServletResponse response){   try{       response.setContentType("text/html");       PrintWriter pwriter = response.getWriter();       HttpSession session=request.getSession(false);       String myName=(String)session.getAttribute("uname");       String myPass=(String)session.getAttribute("upass");       pwriter.print("Name: "+myName+" Pass: "+myPass);       pwriter.close();   }catch(Exception exp){       System.out.println(exp);    }   } }

web.xml

<web-app> <servlet>    <servlet-name>Servlet1</servlet-name>    <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping>    <servlet-name>Servlet1</servlet-name>    <url-pattern>/login</url-pattern> </servlet-mapping> <servlet>    <servlet-name>Servlet2</servlet-name>    <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping>    <servlet-name>Servlet2</servlet-name>    <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>

Output:
First Screen:

After clicking Submit:

After clicking view details:

How To Create Session Object In Java

Source: https://beginnersbook.com/2013/05/http-session/

Posted by: gonzaleztheast.blogspot.com

0 Response to "How To Create Session Object In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel