Spring MVC-会话差异


问题内容

通过控制器的方法获得会话HttpServletRequest.getSession()HttpSession注入之间有什么区别吗?


问题答案:

基本上,session注入到 Spring MVC 控制器中的对象之间没有区别:

@RequestMapping(value = "/somepath", method = RequestMethod.POST)
@ResponseBody
public JsonResponse someMethod (HttpSession session)
{
 // play with session attributes
}

以及session从中检索的对象HttpServletRequest

@RequestMapping(value = "/somepath", method = RequestMethod.POST)
@ResponseBody
public JsonResponse someMethod (HttpServletRequest request)
{
  Session session = request.getSession();
  // You are playin with the same session attributes.
}

前一种样式只是HttpSession通过将其作为控制器参数注入而为您提供了获取上下文对象的便利,以便 Spring 可以为您处理所有脏东西。