简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM