SpringMvc之值获取Session的两种方法-yellowcong
2017-11-18 16:30
489 查看
在SpringMvc中,获取的Session的方法有两种,一种是通过注入HttpServletRequest,然后 再获取,第二种是通过RequestContextHolder (Spring mvc提供的)这个类来获取
可以看到ServletRequestAttributes 包含了Request,Response和Ssession对象
获取后的结果,获取的Session id是不一样的。
最后附上前台代码
通过注入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>
相关文章推荐
- SpringMVC存取Session的两种方法
- hibernate获取session的两种方式分别是openSession() 方法和getCurrentSession() 方法。
- springMVC 中获取request、response、session方法
- SpringMVC存取Session的两种方法
- hibernate两种获取session方法的区别
- SpringMVC存取Session的两种方法 转
- Springmvc获取session,session里存取值得方法
- SpringMVC存取Session的两种方法
- SpringMVC存取Session的两种方法
- Struts2中获取session、request、respsonse的两种方法
- SpringMVC存取Session的两种方法01
- springMVC 中获取session方法
- SpringMVC存取Session的两种方法
- SpringMVC存取Session的两种方法
- Struts2 中action中获取session的两种方法
- SpringMVC存取Session的两种方法
- SpringMVC存取Session的两种方法
- Java获取客户端真实IP地址的两种方法
- SpringMVC系列之(四):SpringMVC请求参数获取的几种方法
- 获取沙盒文件路径的两种方法