1

I use the Struts2 framework and I have a custom interceptor. The interceptor stack is the defaultStack + my custom interceptor at the bottom (right before the action). In the intercept method I use the following code:

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

session.doSomething();

I was wondering why the used methods don't throw any exceptions, and why it isn't necessary to check if(session != null). Is it not possible for those methods to fail to get an instantiated session? Why? Does the servlet-config interceptor have anything to do with this? If session can be null, in what kind of situation does this happen?

Roman C
  • 49,761
  • 33
  • 66
  • 176
user1884155
  • 3,616
  • 4
  • 55
  • 108

1 Answers1

2

Sessions are only rarely null, because:

  1. Unless specifically configured not to, accessing any JSP page creates a session, and
  2. You're calling getSession(true), which creates a session if one doesn't exist.

There's a "createSession" interceptor you can add to the stack if you're running in an environment where a session wouldn't be created automatically. "servletConfig" is not directly involved.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Sessions can be null in case of testing. – coding_idiot Dec 05 '13 at 14:09
  • @coding_idiot Then you're probably testing wrong, because of the reasons I listed. – Dave Newton Dec 05 '13 at 14:20
  • you mean to say, that I should add `createSession` interceptor while testing. I use `StrutsJUnit4TestCase` while testing & I have to put session externally. http://stackoverflow.com/questions/19649952/struts2-3-12-junit4-testcase-request-session-are-null – coding_idiot Dec 05 '13 at 14:35
  • @coding_idiot Personally, I either test my actions as POJOs and don't go through the entire request process (basically re-testing Struts 2 and Java EE), or I use a headless browser when I need full-on integration testing, which is both more realistic, and more complete. – Dave Newton Dec 05 '13 at 14:44