日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SpringBoot-?@SessionAttributes--使用/實例

作者:IT利刃出鞘 更新時間: 2022-07-02 編程語言

簡介

說明

        本文介紹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

前端


原文鏈接:https://blog.csdn.net/feiying0canglang/article/details/125528470

欄目分類
最近更新