Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 992
user533 Avatar asked May 15 '12 10:05

user533


1 Answers

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

like image 199
TomRed Avatar answered Oct 21 '22 12:10

TomRed