Spring中获取Session的方法汇总

Spring中获取Session的方法汇总

Spring:

web.xml

org.springframework.web.context.request.RequestContextListener

在普通bean中使用:

@Autowired

private HttpSession session;

@Autowired

private HttpServletRequest request;

在普通类中使用:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

Spring Boot:

和上面写法一致。

Spring MVC:

必须要有一个request的引用,否则是取不到的。request可以通过控制器传入,有了request自然就可以取到Session了,或者可以通过Spring的WebUtils取Session数据。

拦截器举例:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

String context = (String) WebUtils.getSessionAttribute(request, "context_key");

return context != null ;

}

普通类:

只能在Servlet调用参数,传递过去。

参考:

http://blog.csdn.net/qq_15099611/article/details/50886697

相关推荐