You can obtain the session attributes by asking the ActionContext or implementing SessionAware
. Implementing SessionAware is preferred.
Ask the ActionContext
The session attributes are available on the ActionContext instance, which is made available via ThreadLocal.
Code Block |
---|
Map attibutes = ActionContext.getContext().getSession();
|
Implement SessionAware
Preferred
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
.
- The default stack includes
- Ensure the action implements the
SessionAware
interface.- The
SessionAware
interface defines asetSession
method that sets the session attributes into the action.
- The
- Changes to the action's session map are reflected in the underlying
HttpSession
. You may query, insert, - Ensure that
servletConfig
Interceptor is included in the Action's stack.- The default stack already includes
_ servletConfig_
.
- The default stack already includes
- Edit the Action so that it implements the SessionAware interface.
- The SessionAware interface expects a
setSession
method. You may wish to include a companiongetSession
method.
- The SessionAware interface expects a
- At runtime, call
getSession
to obtain a Map representing the session attributes. - Any changes made to the session Map are reflected in the actual HttpSessionRequest. You may insert and remove session attributes as needed.
Code Block |
---|
Map parameters = this.getSession();
|
Info |
---|
The |
Info |
When 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
@see org.apache.struts.acton2.interceptor.Servlet Config Interceptor