Spring MVC何时会自动装配HttpSession?

编程入门 行业动态 更新时间:2024-10-24 06:39:02
本文介绍了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?

本文发布于:2023-11-13 10:34:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时会   Spring   MVC   HttpSession

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!