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>
阅读全文
0 0
- SpringMvc之值获取Session的两种方法-yellowcong
- SpringMVC存取Session的两种方法
- SpringMVC存取Session的两种方法
- SpringMVC存取Session的两种方法
- 获取session对象的两种方法
- SpringMvc之值(View到Controller)的传递-yellowcong
- Spring-Mvc之表单验证的两种方式-yellowcong
- Struts2 中action中获取session的两种方法
- Struts2中获取session、request、respsonse的两种方法
- hibernate两种获取session方法的区别
- SpringMvc之国际化-yellowcong
- springMVC 中获取session方法
- hibernate获取session的两种方式
- Request获取Session的两种方式
- hibernate获取session的两种方式
- SpringMvc之入门案例-yellowcong
- SpringMvc之文件上传-yellowcong
- SpringMVC之国际化插件-yellowcong
- java 批处理sql语句
- JSTL标签库学习笔记
- java concurrent
- 【云星数据---Apache Flink实战系列(精品版)】:Apache Flink批处理API详解与编程实战026--DateSet实用API详解026
- 地图投影和矢量瓦片详解
- SpringMvc之值获取Session的两种方法-yellowcong
- 怎样获取form-data方式POST的数据
- bitnami redmine3.2.0插件开发
- js获取当前时间是本年第几周
- 设计模式入门篇——EIT造型
- 【云星数据---Apache Flink实战系列(精品版)】:Apache Flink批处理API详解与编程实战027--DateSet实用API详解027
- 这5个方面让你具备真正的交互设计思维
- 【unity】unity相关内容---链接传送门
- PAT乙级1065