简体   繁体   中英

Struts2 session data not available in JSP until I refresh

I'm building a Struts2 application, where data is sent to my application in a request header. I have a custom interceptor that grabs this data and uses it to retrieve some data from the database and store it in the session. I then use this session data in the resultant JSP. One problem: the session variable is null until I refresh the page.

Here is my stack:

<interceptor-stack name="myStack">
    <interceptor-ref name="myInterceptor"/>
    <interceptor-ref name="defaultStack"/>
</interceptor-stack>

Here is my intercept method in myInterceptor:

ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
HttpSession session =  request.getSession(true);

MyObject obj = new MyObject();
String header = request.getHeader("HEADER_VALUE");
if(header != null) {
    obj.loadByHeader(header);
    session.setAttribute("value", obj);
}
return invocation.invoke();

And here is the JSP code:

<s:if test="#session.value == null">
    ...
</s:if>

Like I said, this works when I either refresh or go to another page using this value. Am I doing something wrong? Or can I not get the value until the next time around? If it's the latter, is there an alternative way to get that data on first pass?

You should be able to do set it and use it in one shot! I don't see any issue in what you've provided, my guess would be that you are rendering your view the first time without going though your interceptor.

Two ways this could happen: 1, you have more than one package. One of the packages has your custom interceptor stack defined and the other does not. The one that does not renders the view the first time and then subsequent renderings do pass through your interceptor, 2) it is also possible if you have more than one action which will render the view and you have interceptors being applied at the action level.

Throw print/logging message into the interceptor and make sure it is being executed when you think it is.

Edit : reverse order of defaultStack and myInterceptor since the params interceptor will not have run before myInterceptor.

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