Struts 2 Session in interceptor

Sachin Midha picture Sachin Midha · Aug 12, 2011 · Viewed 10.2k times · Source

I am trying to access session object from within my interceptor by implementing SessionAware interface (I've implemented the setSession method), but I am not able to get my session object this way.

Then I tried ActionContext.getContext().getSession() and I am able to get the session, but I don't know but its coming out to be empty for only the first time in every browser for every user & then it comes filled when another action is invoked.

I assume there is something wrong going with the session. Why is it giving me an empty session only for the first time? Does it set something only after giving empty session for the first time?

If this is the case then everyone will be shown as guest on their first request & then with a username on their 2nd request & hence forth.

Or am I getting the session in the wrong way?

I saw code to get sessions in interceptors, but this does not work for me as it cannot find the constant HTTP_REQUEST.

final ActionContext context = invocation.getInvocationContext();

HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);

HttpSession session = request.getSession(true);

Object user = session.getAttribute(Constants.USER_HANDLE);

Any suggestion on resolving any of the problems?

Something I forgot to mention - my website is a secure site(https), so if the user is not logged in, it would not let him enter the website & if he is logged in, at least his username should be there in the session. Shouldn't it be?

Answer

Shawn D. picture Shawn D. · Aug 12, 2011

I have an interceptor that also grabs the session as a map. Have you tried something like this? This works for me.

public String intercept( ActionInvocation actionInvocation ) throws Exception {
    Map session = actionInvocation.getInvocationContext().getSession();