Reputation: 49
Issues in using AutoWired HttpSession:
LoginController calls LoginService passing HttpServletRequest as parameter.
I've autowired HttpSession like this in few other annotated classes (but NOT in LoginService):
@Autowired
private HttpSession httpSession;
In LoginService class, if I try to get session by calling request.getSession(false)
I receive null in some instances.
If I try to get session by calling request.getSession(true)
I am ending up with two HttpSession objects (one here and another one thru AutoWiring).
If I autowire HttpSession in LoginServic class and use the session from there, then also I am ending with two HttpSession objects.
When exactly autowired HttpSession will be created? What is the best way to handle this situation?
Thanks!
Upvotes: 0
Views: 6766
Reputation: 101
The LoginController is supposed to manage the Web Concern.
The LoginService is supposed to manage the Authentication Concern and not supposed to be aware of the Web Concern.
A HttpSession is a concern of the Web domain. And so, has to be managed in the Class that manage the Web Concern -> the LoginController.
So, the LoginController will declare as a parameter of a Mapped method the HttpSession, and will read/write what it need from the HttpSession and pass it as a parameter of the method called on the LoginService.
Something like :
@Controller
public class ApplicationController {
@Autowired
private LoginService loginService;
@RequestMapping(value = "/login", method = POST)
public void Login(HttpSession httpSession) {
final String myAttribute = String.valueOf(httpSession.getAttribute("myAttribute"));
loginService.doWhatYouNeedToDo(myAttribute);
}
}
Upvotes: 1