Spring在service层获取session和request

获取request有两种方法:

  • 1.在web.xml文件中添加监听器,然后通过注解注入request:

    <listener>    
        <listener-class>    
            org.springframework.web.context.request.RequestContextListener
        </listener-class>    
    </listener>
    @Autowired  
    private HttpServletRequest request; 
  • 2.直接在service层普通类中获取

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

    获取session的方法如下:

  • 在service层注入HttpSession对象,然后直接获取

    @Autowired
    private HttpSession session;
    
    public void getsession (){
        String name = (String) session.getAttribute("name");
    }
posted @ 2018-06-12 11:05  依馨Lina  阅读(11471)  评论(1编辑  收藏  举报