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

    一.for循环语法: for 循环变量初始化:循环条件:循环变量迭代{ 循环体 }案例: 打印10句hello 方式一 package main import "fmt" func ...

  2. javaweb学习笔记(二)

    一.javaweb学习是所需要的细节 1.Cookie的注意点 ① Cookie一旦创建,它的名称就不能更改,Cookie的值可以为任意值,创建后允许被修改. ② 关于Cookie中的setMaxAg ...

  3. (尚004)Vue计算属性之基本使用和监视

    所做效果预览: test004.html <!DOCTYPE html><html lang="en"><head> <meta char ...

  4. DEV C++的使用

    1.点击dev图标: 2.左上角点击:文件——新建——源代码(快捷键ctrl+N): 3. 然后开始写代码: 4.点击运行: 右边的那个编译加运行(点这个),左边编译,中间运行. 5.保存(可以修改保 ...

  5. 备用shell管理方案之butterfly+nginx+https

    安装butterfly+nginx https 1. 安装butterfly yum install python36 python36-pip python36-devel -y pip insta ...

  6. (6)Go函数和函数式编程

    一.Go函数 函数是组织好的.可重复使用的.用于执行指定任务的代码块.本文介绍了Go语言中函数的相关内容. Go语言中支持函数.匿名函数和闭包,并且函数在Go语言中属于"一等公民" ...

  7. P2258 子矩阵——搜索+dp

    P2258 子矩阵 二进制枚举套二进制枚举能过多一半的点: 我们只需要优化一下第二个二进制枚举的部分: 首先我们先枚举选哪几行,再预处理我们需要的差值,上下,左右: sum_shang,sum_hen ...

  8. ROS里程计的学习

    采用增量式编码器来实现odometry的计算,首先采用编码器对脉冲进行采样实现左右轮运动状态的获取,然后再利用增量式测程法得到机器人车体当前坐标系的位姿. 增量式测量法是使用从编码器采样到的数据并依据 ...

  9. FLUENT不同求解器离散格式选择【转载】

    转载自:http://blog.163.com/wu_yangfeng/blog/static/16189737920104158950438/ 离散格式对求解器性能的影响 控制方程的扩散项一般采用中 ...

  10. nodejs express cheerio request爬虫

    const express = require('express') const cheerio = require('cheerio') const request = require(" ...