使用AutoWired HttpSession出现的问题:
Issues in using AutoWired HttpSession:
LoginController调用LoginService并传递HttpServletRequest作为参数.
LoginController calls LoginService passing HttpServletRequest as parameter.
我已经在其他一些带注释的类中(但不是在LoginService中)自动连接了HttpSession:
I've autowired HttpSession like this in few other annotated classes (but NOT in LoginService):
@Autowired private HttpSession httpSession;在LoginService类中,如果我尝试通过调用request.getSession(false)来获取会话,则在某些情况下会收到null.
In LoginService class, if I try to get session by calling request.getSession(false) I receive null in some instances.
如果我尝试通过调用request.getSession(true)来获取会话,那么我将获得两个HttpSession对象(一个在这里,另一个通过自动装配).
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).
如果我在LoginServic类中自动连接HttpSession并从那里使用会话,那么我也将以两个HttpSession对象结束.
If I autowire HttpSession in LoginServic class and use the session from there, then also I am ending with two HttpSession objects.
何时将创建完全自动连线的HttpSession?处理这种情况的最佳方法是什么?
When exactly autowired HttpSession will be created? What is the best way to handle this situation?
谢谢!
推荐答案LoginController应该用于管理Web关注. LoginService应该管理身份验证问题,而不应该了解Web问题. HttpSession是Web域的关注点.因此,必须在管理Web关注的类-> LoginController中进行管理. 因此,LoginController将HttpSession声明为Mapped方法的参数,并将从HttpSession读取/写入所需的内容,并将其作为LoginService上调用的方法的参数进行传递. 像这样的东西:
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); } }更多推荐
Spring MVC何时会自动装配HttpSession?
发布评论