Skip to end of metadata
Go to start of metadata

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.


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.

Enterprise Solution Architecture
Cody Burleson is an Enterprise Web Architect, entrepreneur, and writer. He designs and builds solutions with his team at Base22 using IBM WebSphere Portal, IBM Web Content Manager, IBM Connections, and Java/J2EE. He is a tireless student of information technology who loves to invent things, improve things, and share what he learns. You can find more at his blog,

  • No labels


  1. Anonymous

    if you use the 'this' qualifier in front of session the setter should work. eg.

  2. Anonymous

    could you tell me the mechanism whey the method parameter variable should distinctly different than the action's representative field name