Should I get the session through SessionAware or ActionContext?

user663724 picture user663724 · Sep 13, 2011 · Viewed 7.8k times · Source

After reading the differences between obtaining the session map via ActionContext.getContext().getSession() and having it injected through SessionAware I was wondering which is the preferred method, and why?

The API recomends to use SessionAware, and I read on the web that using SessionAware makes the application easier to test--is testing the only issue?

Can someone elaborate a little bit on this subject or point out to references explaining this?

Answer

Umesh Awasthi picture Umesh Awasthi · Sep 13, 2011

I have already replied the same in your earlier question.you can use either way or even can get access to the Session by more ways.

one way

Map attibutes = ActionContext.getContext().getSession();

But if you use this and your action class is directly tied to the ActionContext which is Struts2 specific way. One of the prime goal of Struts2 is to decouple Action classes from underlying HTTP context as well with other direct dependencies. Also writing test cases for plain POJO is way easy and better than the other way.

By implementing SessionAware interface you are indicating Struts2 that you want session as a simple map object, this not only making code much decoupled but easy to maintain and test.

I hope some one else will come with more good points on this