Spring MVC何时会自动装配HttpSession? [英] Spring MVC when autowired HttpSession will be created?

查看:321
本文介绍了Spring MVC何时会自动装配HttpSession?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆