SpringMVC使用session保存数据以及applicat
2020-11-27 本文已影响0人
凡哥爱丽姐
使用session保存数据(session是一次会话,里面可以有多次请求)
1、HttpSession session
1.1、index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<form action="/test" method="post" >
<input type="text" name="username"><br/>
<input type="text" name="password"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
1.2、success.jsp
<%--
Created by IntelliJ IDEA.
User: Mr Wei
Date: 2020/10/27
Time: 9:18
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
<title>成功页面</title>
</head>
<body>
<h1>测试成功!</h1>
<h2>model</h2>
username:${uname}
<h2>session</h2>
sessionname:${sessionname}<br/>
<a href="/logout">out</a>
</body>
</html>
1.3、测试类
@Controller
public class TestModelController {
@RequestMapping("/test")
public String test(String username, String password, ModelMap modelMap, HttpSession session,HttpServletRequest request){
System.out.println(username+" "+password);
modelMap.addAttribute("uname",username);
session.setAttribute("sessionname",username);
return "success";
}
@RequestMapping("/logout")
public String logout(HttpSession session){
session.invalidate();//让session失效
return "index";
}
}
测试结果
图片.png图片.png
注:只有点out,session才会在这次会话中失效
2、使用@sessionAttributes("key值") //写的是ModelMap中定义的key值
注:该注解和ModelMap结合使用,当使用ModelMap存值时,会在session中同时存储一份数据
@SessionAttributes()的小括号中如果是一个值,不要加{}
示例:
@SessionAttributes("key")
@SessionAttributes({"key1","key2"})
清除注解SessionStatus status类
status.setComplete();
2.1、index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<form action="/test" method="post" >
<input type="text" name="username"><br/>
<input type="text" name="password"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
2.2、success.jsp
<%--
Created by IntelliJ IDEA.
User: Mr Wei
Date: 2020/10/27
Time: 9:18
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
<title>成功页面</title>
</head>
<body>
<h1>测试成功!</h1>
<h2>model</h2>
username:${uname}
<h2>SessionAttributes</h2>
SessionAttributesName:${uname}<br/>
<a href="/logout">out</a>
</body>
</html>
3.2、测试类
@Controller
@SessionAttributes("uname")
public class TestModelController {
@RequestMapping("/test")
public String test(String username, String password, ModelMap modelmap){
System.out.println(username+" "+password);
modelmap.addAttribute("uname",username);
return "success";
}
@RequestMapping("/logout")
public String logout(SessionStatus status){
status.setComplete();//清除session
return "index";
}
}
测试结果
图片.png3、applicationContext作用域
图片.png图片.png