SpringMVC 存取session数据实例(@SessionAttributes 注解)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38737992/article/details/89763067

1. 概述

SpringMVC 可以通过 @SessionAttributes 添加session。

@SessionAttributes 要在类上声明,如下所示。

@SessionAttributes 有三个属性:

(1)names:声明需要存储到session中数据的名称。

(2)types:声明存储到session中参数类型,将模型中对应类型的参数存储到session中。

(3)value:其实和names是一样的。names 和 value 同时使用会报错。

举个例子,数据名称为"me" 或 "he" 存储到session中,类型为double 或 int 的参数存储到session中。

@SessionAttributes(names={"me","he"}, types = {Double.class, Integer.class})

2. 实例

控制器中的测试代码:

    @RequestMapping("/testSessionAttributes")
    public String testSessionAttributes(Model model, String name, HttpSession session) {
        model.addAttribute("me", "me: " + name);
        model.addAttribute("he", "he: " + name);
        model.addAttribute("she", "she: " + name);
        model.addAttribute("double", 1.11);
        model.addAttribute("int", 1024);
        return "page2";
    }

视图,page2.jsp :

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

${sessionScope.get("me")}
<br/><hr/>
${sessionScope.get("he")}
<br/><hr/>
${sessionScope.get("double")}
<br/><hr/>
${sessionScope.get("int")}
<br/><hr/>
${sessionScope.get("she")}

</body>
</html>

访问http://localhost:8080/testSessionAttributes.form?name=syrdbt,she数据没有存到session中,因为没有声明,运行截图:

3.  多个Controller 访问session 

控制器中的测试代码如下:

    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap) {
        System.out.println(modelMap.get("me"));
        System.out.println(modelMap.get("he"));
        System.out.println(modelMap.get("she"));
        return "page2";
    }

访问 http://localhost:8080/testModelMap.form,运行截图:

 

猜你喜欢

转载自blog.csdn.net/qq_38737992/article/details/89763067
今日推荐