2

There are many ways to get session object in struts2. Which one is best and recommended approach to get session object from the following?.

  1. ActionContext
  2. SessionAware
  3. Getting Request from ServletRequestAware and after session from request object.

Now I am using ServletRequestAware for getting session object in all actions even though request object is not needed.

Which one is best and Why it is best?

Thanks in advance

Roman C
  • 49,761
  • 33
  • 66
  • 176
dbyuvaraj
  • 487
  • 1
  • 6
  • 20

2 Answers2

3

Implementing SessionAware is preferred although you can access the session in other ways you stated too.
By implementing SessionAware you give struts2 a chance to inject the session attributes (Which is the map) into your action. This keeps your code clean from coupling to underlying servlet context and also makes testing easier since you can pass any map object to your action with desired attributes. Also any change made to this session map will be reflected on the real session object.

doctrey
  • 1,227
  • 1
  • 12
  • 25
  • Thanks doctrey for the useful explanation.. Can I get **servletContext** from the session object of SessionAware without using ServletRequestAware because I need to get the real path of the server? – dbyuvaraj Jul 18 '11 at 05:33
  • @yuvaraj You're welcome. If you need access to **servletContext** just implement `ServletContextAware`. – doctrey Jul 19 '11 at 07:05
  • Thank you for your hint, doctrey – dbyuvaraj Jul 21 '11 at 04:52
0

agree with doctrey. make your action implements sessionaware, and create the session variable (which is Map variable). that variable can be treated just like any ordinary variable. the code will looks tidier.

fajrian
  • 527
  • 1
  • 4
  • 14