SpringMvc之值获取Session的两种方法-yellowcong

来源:互联网 发布:夏宽大师 淘宝 编辑:程序博客网 时间:2024/06/09 10:22

在SpringMvc中,获取的Session的方法有两种,一种是通过注入HttpServletRequest,然后 再获取,第二种是通过RequestContextHolder (Spring mvc提供的)这个类来获取

通过注入HttpServletRequest

获取到HttpServletRequest后,再获取Session啥的都不是麻烦事了

    /**     * 通过注入Request的方式来获取session     * @param request     * @return     */    @RequestMapping(value="/login",method=RequestMethod.GET)    public String login1(HttpServletRequest request) {        //获取到Session对象        HttpSession session = request.getSession();        //往Session中放入数据        session.setAttribute("username", "yellowcong");        session.setAttribute("password", "doubi");        return "demo/session";    }

RequestContextHolder 获取Session

通过这个方法不仅可以获取到Session,而且可以获取到HttpServletRequest,HttpServletResponse的对象

/**     * 通过Springmvc的内置对象来获取     * @return     */    @RequestMapping(value="/login2",method=RequestMethod.GET)    public String login2(){        //获取到Session对象        HttpSession session = getSession();        //往Session中放入数据        session.setAttribute("username", "yellowcong_test");        session.setAttribute("password", "doubi_test");        session.setAttribute("sessionId", session.getId());        //跳转到页面        return "demo/session";    }    /**     * 在SpringMvc中获取到Session     * @return     */    public HttpSession getSession(){        //获取到ServletRequestAttributes 里面有         ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();        //获取到Request对象        HttpServletRequest request = attrs.getRequest();        //获取到Session对象        HttpSession session = request.getSession();        //获取到Response对象        //HttpServletResponse response = attrs.getResponse();        return session;    }

可以看到ServletRequestAttributes 包含了Request,Response和Ssession对象

这里写图片描述

获取后的结果,获取的Session id是不一样的。
这里写图片描述

这里写图片描述

最后附上前台代码

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%><html><head><title>xx文章</title></head><body><!-- ${user.username} 这个访问了  用户model里面的属性 --><h2>${username} -${password}-${sessionId }</h2></body></html>
原创粉丝点击