How to get session value from one servlet to another servlet

In one servlet, I have four variables. I want all these four variables to be extracted to another servlet.

I used the code in servlets 1 as follows.

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

In another servlet, I tried to get the value using code.

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

I think there is a clear way to track session variables.

I saw on the net, but everybody bothers me ..

Please help me..

+4
source share
1 answer

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

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

:

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

to retrieve:

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

getSession (true) means creating a session if it does not exist. getSession (false) equals getSession. Finally, if you want to remove the attribute from the session from this point, you can use

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

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

Tomred

+12
source

Source: https://habr.com/ru/post/1412555/


All Articles