【问题标题】:Spring MVC when autowired HttpSession will be created?Spring MVC何时会创建自动装配的HttpSession?
【发布时间】:2017-04-30 07:50:08
【问题描述】:

使用 AutoWired HttpSession 的问题:

LoginController 调用 LoginService 传递 HttpServletRequest 作为参数。

我已经在其他几个带注释的类中像这样自动装配了 HttpSession(但不在 LoginService 中):

@Autowired 
private HttpSession httpSession;

在 LoginService 类中,如果我尝试通过调用 request.getSession(false) 来获取会话,我在某些情况下会收到 null。

如果我尝试通过调用 request.getSession(true) 来获取会话,我最终会得到两个 HttpSession 对象(一个在这里,另一个通过 AutoWiring)。

如果我在 LoginServic 类中自动装配 HttpSession 并从那里使用会话,那么我也会以两个 HttpSession 对象结束。

什么时候会创建自动装配的 HttpSession?处理这种情况的最佳方法是什么?

谢谢!

【问题讨论】:

  • 欢迎来到 Stack Overflow!请查看我们的SO Question Checklist 以帮助您提出一个好问题,从而得到一个好的答案。
  • 非常不清楚你在问什么,但最好的方法是使用 Spring Security 而不是自己编写安全代码。
  • 鉴于我们项目的当前时间,我不能使用 Spring Security。如果您按照提到的步骤进行操作,您将理解我的问题。如果您在任何步骤中不清楚,请告诉我,我可以纠正。简而言之,我需要知道 AutoWired HttpSession 的确切创建时间以及如何使用它。
  • 您的问题在这里得到解答。 stackoverflow.com/questions/41153689/…

标签: java spring model-view-controller autowired httpsession


【解决方案1】:

LoginController 应该管理 Web Concern。
LoginService 应该管理 Authentication Concern,而不应该知道 Web Concern。
HttpSession 是 Web 域的关注点。因此,必须在管理 Web Concern 的类中进行管理 -> LoginController。
因此,LoginController 会将 HttpSession 声明为 Mapped 方法的参数,并将从 HttpSession 读取/写入所需的内容,并将其作为 LoginService 上调用的方法的参数传递。
类似的东西:

@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);
}
}

【讨论】:

  • 我遇到的问题是:传递给 Login 方法的 httpSession 与自动装配的 httpSession 不同,最终得到两个不同的 httpSession 对象。
  • @Swamy 你解决了你的问题吗?我遇到了同样的问题!我的 httpsession 在我的登录过程中与在我的休息呼叫中不同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
相关资源
最近更新 更多