问题
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?
回答1:
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
回答2:
SessionAware
is a dependency injection approach, whereas ActionContext.getContext().getSession()
is not. Otherwise, they are identical. Both of these approaches return you a Map<String, Object>
as opposed to the HttpSession
which is part of the servlet API.
来源:https://stackoverflow.com/questions/7401576/should-i-get-the-session-through-sessionaware-or-actioncontext