springMVC笔记系列(15)——模型数据处理篇 之 @Session注解

来源:互联网 发布:vb游戏代码大全 编辑:程序博客网 时间:2024/05/21 07:06

说明:本文章的内容转载至:https://my.oschina.net/happyBKs/blog/420310
如有侵权的地方,请联系本人,本人将会立即删除!

前面我们都是讲模型数据放到请求里面,那么可不可以将模型数据放到Session里面呢?这就要用到@Session注解。

@SessionAttributes

• 若希望在多个请求之间共用某个模型属性数据,则可以在控制器类上标注一个 @SessionAttributes, Spring MVC将在模型中对应的属性暂存到 HttpSession 中。

• @SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外,还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中

– @SessionAttributes(types=User.class) 会将隐含模型中所有类型为 User.class 的属性添加到会话中。

– @SessionAttributes(value={“user1”, “user2”})

– @SessionAttributes(types={User.class, Dept.class})

– @SessionAttributes(value={“user1”, “user2”},types={Dept.class})

我们下面做个实验:

控制器类实现如下:

package com.happyBKs.springmvc.handlers;import java.util.Map;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.SessionAttributes;import com.happyBKs.springmvc.beans.Sword;@SessionAttributes(value="SW1",types={String.class})@RequestMapping("/model")@Controllerpublic class ModelDataHandlerSession {    /*     *      * @SessionAttributes      * 除了可以通过属性名指定需要放到会话中的属性外,(实际上使用的是value属性值)     * 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使用的是types属性值)     *      * 注意:该注解只能放在类的上面而不能放在方法上面     */    @RequestMapping("/sessiontest")    public String handle1(Map<String,Object> map)    {        String returnStr="SessionAnnotationTest";        Sword s=new Sword("水晶剑", 40);        map.put("SW1", s);        map.put("myname", "happyBKs");        map.put("age", 100);        return returnStr;    }}

请求也设计如下:为的是验证利用value、types如何对模型数据是否传入session域进行控制。

第一个Sword类型的数据是因为注解value有了模型数据的名称即“SW1”所以能够进入Session域。

第二个是制定了所有模型数据是String类型的都能够加入Session域,所以注解value中虽然没有“myname”,但是types里有String,所以第二个也可以传入Session域。

第三个是个反例,不再陈述。

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ page isELIgnored="false"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body>example1:SW1<br>Request:${requestScope.SW1}<br>Session:${sessionScope.SW1}<br>example1:myname<br>Request:${requestScope.myname}<br>Session:${sessionScope.myname}<br>example1:age<br>Request:${requestScope.age}<br>Session:${sessionScope.age}<br></body></html>

运行请求结果如下:
这里写图片描述

这里有个题外话,注意:如果在EL表达式中没有注明requestScope后sessionScope,默认是请求域。

0 0
原创粉丝点击