Issue
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..
Solution
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
Answered By - TomRed
Answer Checked By - Willingham (JavaFixing Volunteer)