How can I get stored session values in multiple Struts 2 action classes?
I do not want to use SessionAware
interface in all the actions.
You have three options:
SessionAware
.SessionAware
.ActionContext
:Map attibutes = ActionContext.getContext().getSession();
Documented on the Struts 2 wiki under How do we get access to the session.
Why wouldn't you want to use SessionAware
and make your actions more-easily testable?
SessionAware
in multiple classes then at least you can use one abstract class or interface your action classes extend. It will inject a SessionMap
to your action class instances.Other ways to obtain a SessionMap
or directly HttpSession
are from here:
If you want to put something to the session you should get the session map from the action context
Map<String, Object> session = >ActionContext.getContext().getSession(); session.put("username", username); session.put("role", 1);
or use servlet session directly
HttpSession session = >ServletActionContext.getRequest().getSession(); session.setAttribute("username", username); session.setAttribute("role", 1);
But the first case is preferable, due to it's supported by the framework.
More other options (you have at least another five options):
scopedModelDriven
interceptor;scope
interceptor;