Spring MVC - 会话差异

sid*_*nks 3 java session servlets spring-mvc httpsession

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

tma*_*wen 5

session注入Spring MVC控制器的对象基本上没有区别:

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

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.
}
Run Code Online (Sandbox Code Playgroud)

前一种风格只是HttpSession通过将其作为控制器参数注入来为您提供获取上下文对象的工具,以便Spring为您处理所有脏东西.