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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

SpringBoot-?@SessionAttributes--使用/實(shí)例

作者:IT利刃出鞘 更新時(shí)間: 2022-07-02 編程語(yǔ)言

簡(jiǎn)介

說(shuō)明

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

概述

        在默認(rèn)情況下,ModelMap中的屬性作用域是request級(jí)別,也就是說(shuō),當(dāng)本次請(qǐng)求結(jié)束后,ModelMap 中的屬性將銷毀。如果希望在多個(gè)請(qǐng)求中共享ModelMap中的屬性,必須將其屬性轉(zhuǎn)存到session 中,這樣 ModelMap 的屬性才可以被跨請(qǐng)求訪問(wèn)。

        Spring 允許我們有選擇地指定 ModelMap 中的哪些屬性需要轉(zhuǎn)存到 session 中,以便下一個(gè)請(qǐng)求屬對(duì)應(yīng)的 ModelMap 的屬性列表中還能訪問(wèn)到這些屬性。這一功能是通過(guò)類定義處標(biāo)注 @SessionAttributes 注解來(lái)實(shí)現(xiàn)的。

代碼

后端代碼

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...");
        // 底層會(huì)存儲(chǔ)到request域?qū)ο笾?
        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域中的存入的數(shù)據(jù)
	    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>

測(cè)試

測(cè)試1

訪問(wèn):http://localhost:8080/anno/testSessionAttributes/

前端

測(cè)試2

訪問(wèn):http://localhost:8080/anno/getSessionAttributes/

后端打印

getSessionAttributes...
testSessionAttributes

測(cè)試3

訪問(wèn):http://localhost:8080/anno/getSessionAttributes/

測(cè)試4

再次訪問(wèn):http://localhost:8080/anno/getSessionAttributes/

后端打印

getSessionAttributes...
null

前端


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

欄目分類
最近更新