在开发控制器的时候,有时也需要保存对应的数据到这些对象中去,或者从中获取数据。而Spring MVC给予了支持,它的主要注解有3个:@RequestAttribute、@SessionAttribute和@SessionAttributes,它们的作用如下。
•@RequestAttribute获取HTTP的请求(request)对象属性值,用来传递给控制器的参数。
•@SessionAttribute在HTTP的会话(Session)对象属性值中,用来传递给控制器的参数。
•@SessionAttributes,可以给它配置一个字符串数组,这个数组对应的是数据模型对应的键值对,然后将这些键值对保存到Session中。
注解@RequestAttribute
@RequestAttribute主要的作用是从HTTP的request对象中取出请求属性,只是它的范围周期是在一次请求中存在
代码清单15-23:请求属性 requestAttribute.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!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> <% //设置请求属性 request.setAttribute("id", 111L); //转发给控制器 request.getRequestDispatcher("../attribute/requestAttribute.do").forward(request, response); %> </body> </html>
代码清单15-24:控制器获取请求属性
package com.ssm.chapter15.controller; import com.ssm.chapter15.pojo.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; @Controller @RequestMapping("/attribute") public class AttributeController { // @Autowired // private RoleService roleService; @RequestMapping("/requestAttribute") public ModelAndView reqAttr(@RequestAttribute(value = "id", required = false) Long id) { System.out.println("id =>" + id); ModelAndView mv = new ModelAndView(); // Role role = roleService.getRole(id); // mv.addObject("role", role); mv.addObject("role", id); mv.setView(new MappingJackson2JsonView()); return mv; } }
注解@SessionAttribute和注解@SessionAttributes
这两个注解和HTTP的会话对象有关,在浏览器和服务器保持联系的时候HTTP会创建一个会话对象,这样可以让我们在和服务器会话期间(请注意这个时间范围)通过它读/写会话对象的属性,缓存一定数据信息。
先来讨论一下设置会话属性,在控制器中可以使用注解@SessionAttributes来设置对应的键值对,不过这个注解只能对类进行标注,不能对方法或者参数注解。它可以配置属性名称或者属性类型。它的作用是当这个类被注解后,Spring MVC执行完控制器的逻辑后,将数据模型中对应的属性名称或者属性类型保存到HTTP的Session对象中。
代码清单15-25:使用注解@SessionAttributes
package com.ssm.chapter15.controller; import com.ssm.chapter15.pojo.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; @Controller @RequestMapping("/attribute") //可以配置数据模型的名称和类型,两者取或关系 @SessionAttributes(names = {"id"}, types = {Role.class}) public class AttributeController { @RequestMapping("/sessionAttributes") public ModelAndView sessionAttrs(Long id) { ModelAndView mv = new ModelAndView(); // Role role = roleService.getRole(id); Role role = new Role(id, "射手", "远程物理输出"); //根据类型,Session将会保存角色信息 mv.addObject("role", role); // 根据名称,Session将会保存id mv.addObject("id", id); //视图名称,定义跳转到一个JSP文件上 mv.setViewName("sessionAttribute"); return mv; } }
代码清单15-26:sessionAttribute.jsp验证注解有效性
<%@ page language="java" import="com.ssm.chapter15.pojo.Role" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!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> <% Role role = (Role) session.getAttribute("role"); out.println("id = " + role.getId() + "<p/>"); out.println("roleName = " + role.getRoleName() + "<p/>"); out.println("note = " + role.getNote() + "<p/>"); Long id = (Long) session.getAttribute("id"); out.println("id = " + id + "<p/>"); %> </body> </html>
读取Session的属性,Spring MVC通过@SessionAttribute实现。
代码清单15-27:JSP设置Session属性 sessionAttribute.jsp
<%@ page language="java" import="com.ssm.chapter15.pojo.Role" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!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> <% Role role = (Role) session.getAttribute("role"); out.println("id = " + role.getId() + "<p/>"); out.println("roleName = " + role.getRoleName() + "<p/>"); out.println("note = " + role.getNote() + "<p/>"); Long id = (Long) session.getAttribute("id"); out.println("id = " + id + "<p/>"); %> </body> </html>
代码清单15-28:获取Session属性
package com.ssm.chapter15.controller; import com.ssm.chapter15.pojo.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; @Controller @RequestMapping("/attribute") //可以配置数据模型的名称和类型,两者取或关系 @SessionAttributes(names = {"id"}, types = {Role.class}) public class AttributeController { @RequestMapping("/sessionAttribute") public ModelAndView sessionAttr(@SessionAttribute("id") Long id) { System.out.println("id =>" + id); ModelAndView mv = new ModelAndView(); // Role role = roleService.getRole(id); Role role = new Role(id, "射手", "远程物理输出"); mv.addObject("role", role); mv.setView(new MappingJackson2JsonView()); return mv; } }
注解@CookieValue和注解@RequestHeader
从名称而言,这两个注解都很明确,就是从Cookie和HTTP请求头获取对应的请求信息,它们的用法比较简单,且大同小异,所以放到一起讲解。只是对于Cookie而言,用户是可以禁用的,所以在使用的时候需要考虑这个问题。下面给出它们的一个实例,如代码清单15-29所示。
代码清单15-29:使用@CookieValue和@RequestHeader
package com.ssm.chapter15.controller; import com.ssm.chapter15.pojo.Role; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @RequestMapping("/cookie") public class CooKieController { @RequestMapping("/getHeaderAndCookie") public String testHeaderAndCookie(@RequestHeader(value = "User-Agent", required = false, defaultValue = "attribute") String userAgent , @CookieValue(value = "JSESSIONID", required = true, defaultValue = "MyJsessionId") String jsessionId) { System.out.println("User-Agent:" + userAgent); System.out.println("JSESSIONID:" + jsessionId); return "index"; } }