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.

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.

About the author

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, codyburleson.com.