How do I store a value in session that has to be later accessed upon a callback request from a 3rd party site?
I want to store a variable in session data, in a servlet. The servlet redirects the user to a 3rd party site, and from the 3rd party site user is sent to JSP page in same web app. I want to access a session variable stored by servlet (before redirection to 3rd party site) in the JSP. How do I store such an object in servlet? And how do I access that object from开发者_运维问答 JSP file?
You just need to make sure that the callback request instructs the server somehow to use the same session as the initial request. Normally, this is to be done by setting the session cookie in the request header. But a 3rd party site isn't going to do that. However, the Servlet API offers you the possibility to identify the session by the JSESSIONID
fragment in the URL.
So if you construct your callback URL like follows,
HttpSession session = request.getSession();
session.setAttribute("someName", someObject);
String callbackURL = "http://yourhost.com/callback.jsp;JSESSIONID=" + session.getId();
String redirectURL = "http://otherhost.com/process?callbackURL=" + URLEncoder.encode(callbackURL, "UTF-8");
response.sendRedirect(redirectURL);
This way the callback.jsp
will have access to the same session and thus also all stored attributes. By the way, you should really use a servlet with doGet()
here, preprocessing Java code doesn't belong in a JSP.
Apart from the concrete question, there's another way to achieve this: store the information of interest in the application scope by a long, auto-generated and unique key (e.g. java.util.UUID
) and add it as request parameter to the callback URL. When the callback is to be processed, just obtain it from application scope instead of session scope. This is usually to be done inside a popup window which refreshes the parent window and closes itself after successfully processing the callback by JavaScript. This way you don't need to worry about the session.
精彩评论