SpringBoot-@SessionAttributes--使用/实例

原文网址:SpringBoot-​@SessionAttributes--使用/实例_IT利刃出鞘的博客-CSDN博客

简介

说明

        本文介绍SpringBoot中@SessionAttributes的用法。

概述

        在默认情况下,ModelMap中的属性作用域是request级别,也就是说,当本次请求结束后,ModelMap 中的属性将销毁。如果希望在多个请求中共享ModelMap中的属性,必须将其属性转存到session 中,这样 ModelMap 的属性才可以被跨请求访问。

        Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。

代码

后端代码

Controller

@Controller
@RequestMapping("/anno")
@SessionAttributes(value={"msg"})   // 把Mapmodel中名字为msg的属性存入到session属性列表中
public class AnnoController {
    @RequestMapping(value="/testSessionAttributes")
    public String testSessionAttributes(Model model){
        System.out.println("testSessionAttributes...");
        // 底层会存储到request域对象中
        model.addAttribute("msg","testSessionAttributes");
        return "success";
    }

	@RequestMapping(value="/getSessionAttributes")
	public String getSessionAttributes(ModelMap modelMap){
	    System.out.println("getSessionAttributes...");
	    String msg = (String) modelMap.get("msg");
	    System.out.println(msg);
	    return "success";
	}

	@RequestMapping(value="/delSessionAttributes")
	public String delSessionAttributes(SessionStatus status){
	    status.setComplete();//删除session域中的存入的数据
	    return "success";
	}
}

前端代码

success.html

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门成功</h3>
    ${ msg }
    ${sessionScope}
</body>
</html>

测试

测试1

访问:http://localhost:8080/anno/testSessionAttributes/

前端

测试2

访问:http://localhost:8080/anno/getSessionAttributes/

后端打印

getSessionAttributes...
testSessionAttributes

测试3

访问:http://localhost:8080/anno/getSessionAttributes/

测试4

再次访问:http://localhost:8080/anno/getSessionAttributes/

后端打印

getSessionAttributes...
null

前端

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/125528470