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

梦想与她 提交于 2019-12-25 03:28:25

问题


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


回答1:


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

should work.

You can then later retrieve the data

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



回答2:


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/



来源:https://stackoverflow.com/questions/6841838/java-how-to-initialise-session-in-second-servlet-to-get-data-stored-by-first-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!