首页 > 编程语言 > 详细

Spring中获取Session的方法汇总

时间:2017-08-31 19:39:17      阅读:356      评论:0      收藏:0      [点我收藏+]

Spring:

web.xml

<listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

在普通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

Spring中获取Session的方法汇总

原文:http://www.cnblogs.com/EasonJim/p/7460111.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!