To access the session, request, or response from within a Struts 2 action, you can use the ActionContext or implement the SessionAware, ServletRequestAware, or ServletResponseAware interfaces. Implementing the interfaces is preferred because it can make it easier to develop unit tests.
Following is an example action class that implements all three interfaces. Struts will handle setting the appropriate objects for you as long as the the interceptors are defined for the package in struts.xml where the action is defined. Note that these interceptors are already defined for struts-default.
NOTES
If I did not name the method parameter variable distinctly different than the action's representative field name, my session object remained null. This was my faulty case:
Renaming the parameter variable fixed the issue as shown below:
You will likely want to put these in some abstract base action and extend it - rather than defining these things for every action class you create.
To unit test, you'll need to create and set mock objects. Take the following for example:
In the example above, I create a new mock session map. I then put an object in it that I expect to be there. I'm using Spring, so I get a handle on my action class from Spring's application context. Once, I have the action, I call setSession() - passing in my mock session map.
Add Comment