How to retrieve session value from one servlet to another servlet?

38,571

First you need to get the Session object from the request.

This is the HTTPServletRequest object sent to the servlet (you will have access to this in the doGet or doPost method).

to set:

ses = request.getSession(true);
ses.setAttribute("Name","Value");

to retrieve:

request.getSession(false).getAttribute("name")

getSession(true) means create session if one does not exist. getSession(false) is equal to getSession. Finally if you wish to remove the attribute from the session from that point you can use

request.getSession().removeAttribute("Name");

I hope this makes sense to you if you need more look at Java Set, Get and Remove Session Attributes.

TomRed

Share:
38,571
user533
Author by

user533

Updated on July 09, 2022

Comments

  • user533
    user533 almost 2 years

    In one servlet I have four variables. I want all those four variables to be retrieved to another servlet.

    I used the code in servlet 1 as follows.

    import javax.servlet.http.HttpSession;
    
    
    session.setAttribute("id",id);
    

    In the other servlet I tried to get the value by using the code..

    String id = HttpSession.getAttribute("id").toString();
    

    I think there is a clear way to do the tracking of the session variables.

    I have seen in net but all are confusing to me..

    Please help me..