You can obtain the session attributes by implementing SessionAware
or getting them from the ActionContext
.
Implementing SessionAware
This is the preferred mechanism: it makes unit testing easier by allowing simple injection of session attributes instead of having to mock the action context or go through an entire request process.
- Ensure that the action's stack includes the
servletConfig
interceptor.The default stack includes
servletConfig
.
- Ensure the action implements the
SessionAware
interface.The
SessionAware
interface defines asetSession
method that sets the session attributes into the action.
- Changes to the action's session map are reflected in the underlying
HttpSession
. You may query, insert, and remove session attributes as needed.
Info |
---|
The |
Tip |
---|
To unit test a |
Ask the ActionContext
Session attributes are available from the ActionContext
instance, a ThreadLocal
.
Code Block |
---|
Map attibutes = ActionContext.getContext().getSession();
|
@see struts-default.xml
@see org.apache.struts.acton2.interceptor.SessionAware
Method A:
ActionContext.getContext().getSession() (returns Map, works internally using a ThreadLocal)
Method B (Recommended):
Have the action implements SessionAware, and the Session (as a Map) will be set through the setSession(Map) method. This requires that the 'servlet-config' interceptor being included when the particular action is processed.
@see webwork-default.xml
@see com.opensymphony.webwork.interceptor.ServletConfigInterceptor