在开发控制器的时候,有时也需要保存对应的数据到这些对象中去,或者从中获取数据。而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";
} }

Spring MVC 保存并获取属性参数的更多相关文章

  1. Spring MVC(十三)--保存并获取属性参数

    这里的属性参数主要是指通过request.session.cookie等设置的属性,有时候我们需要将一些请求的参数保存到HTTP的request或者session对象中去,在控制器中也会进行设置和获取 ...

  2. Spring MVC在接收复杂集合参数

    Spring MVC在接收集合请求参数时,需要在Controller方法的集合参数里前添加@RequestBody,而@RequestBody默认接收的enctype (MIME编码)是applica ...

  3. spring mvc controller中获取request head内容

    spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...

  4. Java-Spring MVC:JAVA之常用的一些Spring MVC的路由写法以及参数传递方式

    ylbtech-Java-Spring MVC:JAVA之常用的一些Spring MVC的路由写法以及参数传递方式 1.返回顶部 1. 常用的一些Spring MVC的路由写法以及参数传递方式. 这是 ...

  5. Spring MVC 不能正常获取参数的值

    最近在开发时遇到一个非常奇怪的问题,在tomcat8中使用Spring MVC框架,在Controller中的方法参数无法正常获取到相应的值,将tomcat版本换成7.0就解决了. 记录以下解决过程, ...

  6. Spring MVC(四)--控制器接受pojo参数

    以pojo的方式传递参数适用于参数较多的情况,或者是传递对象的这种情况,比如要创建一个用户,用户有十多个属性,此时就可以通过用户的pojo对象来传参数,需要注意的是前端各字段的名称和pojo对应的属性 ...

  7. spring mvc接收JSON格式的参数

    1.配置spring解析json的库   <dependency>         <groupId>org.codehaus.jackson</groupId> ...

  8. Spring MVC(六)--通过URL传递参数

    URL传递参数时,格式是类似这样的,/param/urlParam/4/test,其中4和test都是参数,这就是所谓的Restful风格,Spring MVC中通过注解@RequestMapping ...

  9. Spring mvc 下Ajax获取JSON对象问题 406错误

    我在学习springmvc过程中(我的项目是配置的后缀是.html),从controller返回对象. 如果我不使用 mvc-annotation-driver,而是手动配置,AnnotationMe ...

随机推荐

  1. springboot框架笔记

    01.spring data是一个开源的框架,在这个开源的框架中spring  data  api只是其中的一个模块,只需要编写一个接口继承一个类就行了. 02.spring boot框架底层好像将所 ...

  2. 运算符 & | ^ ~ >> << 讲解

    字节”是byte,“位”是bit :1 byte = 8 bit : char 在java中是2个字节.java采用unicode,2个字节(16位)来表示一个字符. char 16位2个字节 byt ...

  3. GDB的安装

    1.下载GDB7.10.1安装包 #wget http://ftp.gnu.org/gnu/gdb/gdb-7.10.1.tar.gz或者可以远程看下有哪些版本 http://ftp.gnu.org/ ...

  4. [matlab工具箱] 神经网络Neural Net

    //目的是学习在BP神经网络的基础上添加遗传算法,蚁群算法等优化算法来优化网络,这是后话. 先简单了解了MATLAB中的神经网络工具箱,工具箱功能还是非常强大的,已经可以拟合出非常多的曲线来分析了. ...

  5. AtCoder Grand Contest 012题解

    传送门 \(A\) 肯定是后面每两个陪最前面一个最优 typedef long long ll; const int N=5e5+5; int a[N],n;ll res; int main(){ s ...

  6. T-MAX组--项目冲刺(第五天)

    T-MAX组--项目冲刺(第五天) THE FIFTH DAY 项目相关 作业相关 具体描述 所属班级 2019秋福大软件工程实践Z班 作业要求 团队作业第五次-项目冲刺 作业正文 T-MAX组--项 ...

  7. session设置存活时间的三种方式

    在web容器中设置(此处以tomcat为例)在tomcat-5.0.28\conf\web.xml中设置,以下是tomcat 5.0中的默认配置: [html] view plain copy < ...

  8. vmWare安装centos7之后使用yum安装提示there are on enabled repos(修改yum源)

    可以使用这个命令修改yum源 curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.rep ...

  9. .net Core 中DateTime在Linux Docker中与Windows时间不一致

    最近写了一个.net core项目,部署到CentOS并在docker上运行的时候,发现DateTime.Now获取的时间与Windows不一致(定时执行的任务,晚了8个小时),在Windows中可以 ...

  10. Open with Sublime 右键打开

    Open with Sublime Sublime 的右键打开没有了,可以使用下面的bat命令添加.   @echo off SET st3Path=D:\Program Files\Sublime ...