1

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.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Vivek Panday
  • 1,426
  • 2
  • 16
  • 34

2 Answers2

4

You have three options:

  1. Do it right and use SessionAware.
  2. Do it right and use a base action class that uses SessionAware.
  3. Do it wrong and use 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?

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Hi Dave, Good to know diff ways ,once I will put some Key-value in session map with in one Action ,Will I be able to get that same value by using key in Different which is not using/implementing SessionAware interface. ? – Vivek Panday Jun 20 '13 at 13:54
  • @user1859100 Session is session, regardless of how accessed. – Dave Newton Jun 20 '13 at 13:56
0

If you don't want to use 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):

Roman C
  • 49,761
  • 33
  • 66
  • 176