您的位置:首页 > 编程语言 > Java开发

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

2017-11-18 16:30 489 查看
在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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: