Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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

(star) Preferred

or getting them from the ActionContext.

Implementing SessionAware

(star) 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.
    • (info) The default stack includes servletConfig.
  • Ensure the action implements the SessionAware interface.
    • (info) The SessionAware interface defines a setSession 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,
  • Ensure that servletConfig Interceptor is included in the Action's stack.
    • (info) The default stack already includes _ servletConfig_.
  • Edit the Action so that it implements the SessionAware interface.
    • The SessionAware interface expects a setSession method. You may wish to include a companion getSession method.
  • 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 servletConfig interceptor looks for actions implementing SessionAware during request processing. When it finds them it passes the map of session attributes using the action's setSession method.

Info

When the servletConfig Interceptor sees that an Action implements ParameterAware, it passes a Map of the session attributes to the Action's setParameters method. Changes made to the Map are reflected in the runtime HttpSessionRequest.

Tip

To unit test a SessionAware Action, create your own Map with the pertinent session attributes and call setSession as part of the test's setUp method. setup method.

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