Arvind
Arvind

Reputation: 6474

java- how to initialise session in second servlet (to get data stored by first servlet in session variable)

I am storing a variable in session data, from a servlet where the user tries logging in to my application. Now I want to retrieve the user data from session, in another servlet in the same application.

How do I initialise the session variable in the second servlet? Taking "request" as the "HttpServletRequest" do I code the session variable as "HttpSession session = null;" or as "HttpSession session = request.getSession(true);"? Or is it some other way?

Note that in the application flow, the user goes to an external page from the first servlet, and from the external page he is redirected to the second servlet. (The external page basically logs in the user via oauth in Google/Yahoo/Hotmail etc).

Does this mean that I cant use session variables in this case? Do I Have to use application scoped variables?

Please excuse me if my question sounds dumb, today is only the 3rd day of my starting coding in Servlets...

Upvotes: 0

Views: 6183

Answers (2)

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16080

Arvind,

in JSP you use:

   <% Object something = request.getSession().getAttribute( "foo" ) %>

which of course - unsurprisingly - is extremely similar to Thilo's answer... :-)

JSP code is evaluated on the server side, so all you have to is make sure that the JSP is chained from the servlet, eg. servlet does something like a

   response.sendRedirect( "your.jsp" )

/Anders/

Upvotes: 1

Thilo
Thilo

Reputation: 262814

request.getSession().setAttribute("foo", something);

should work.

You can then later retrieve the data

Object something = request.getSession().getAttribute("foo");

Upvotes: 1

Related Questions