Should I get the session through SessionAware or ActionContext?
Asked Answered
D

2

6

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?

Disgust answered 13/9, 2011 at 12:5 Comment(0)
C
2

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

Checkerberry answered 13/9, 2011 at 12:39 Comment(3)
In this answer you said that in first way the action class is tied with struts2 specific class i.e.ActionContext class. In second way also if we implement SessionAware interface to our action class, then also action class is tied with struts2 specific class i.e. SessionAware. Now where is the difference?Meadowlark
@Jagadeesh: When you will go for unit testing, you can simply inject a map while doing unit testing with ActionContext is not that easy...there are more details to this...my suggestion is to just check the documentation and also have a look at both of them to get clear idea.Checkerberry
Thanks for the clarification :)Meadowlark
C
0

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.

Cuttlebone answered 13/9, 2011 at 13:20 Comment(2)
An answer should be answering something but your answer is not. His question was to know which approach is good and to know some advantages and drawbacks of both the approaches. It would be really great if can answer this question in the same way.Meadowlark
@Meadowlark I did provide an answer that explains that the two approaches have the same result, but one follows a dependency injection approach, which as he indicated in his questions is the preferred approach. You're welcome to provide your own answer if you want.Cuttlebone

© 2022 - 2024 — McMap. All rights reserved.