• Spring中获取Session的方法汇总


    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

  • 相关阅读:
    @atcoder
    @loj
    @AGC037
    @uoj
    @uoj
    @loj
    @loj
    @loj
    @loj
    @loj
  • 原文地址:https://www.cnblogs.com/EasonJim/p/7460111.html
Copyright © 2020-2023  润新知