Spring MVC 保存并获取属性参数
在开发控制器的时候,有时也需要保存对应的数据到这些对象中去,或者从中获取数据。而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 保存并获取属性参数的更多相关文章
- Spring MVC(十三)--保存并获取属性参数
这里的属性参数主要是指通过request.session.cookie等设置的属性,有时候我们需要将一些请求的参数保存到HTTP的request或者session对象中去,在控制器中也会进行设置和获取 ...
- Spring MVC在接收复杂集合参数
Spring MVC在接收集合请求参数时,需要在Controller方法的集合参数里前添加@RequestBody,而@RequestBody默认接收的enctype (MIME编码)是applica ...
- spring mvc controller中获取request head内容
spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...
- Java-Spring MVC:JAVA之常用的一些Spring MVC的路由写法以及参数传递方式
ylbtech-Java-Spring MVC:JAVA之常用的一些Spring MVC的路由写法以及参数传递方式 1.返回顶部 1. 常用的一些Spring MVC的路由写法以及参数传递方式. 这是 ...
- Spring MVC 不能正常获取参数的值
最近在开发时遇到一个非常奇怪的问题,在tomcat8中使用Spring MVC框架,在Controller中的方法参数无法正常获取到相应的值,将tomcat版本换成7.0就解决了. 记录以下解决过程, ...
- Spring MVC(四)--控制器接受pojo参数
以pojo的方式传递参数适用于参数较多的情况,或者是传递对象的这种情况,比如要创建一个用户,用户有十多个属性,此时就可以通过用户的pojo对象来传参数,需要注意的是前端各字段的名称和pojo对应的属性 ...
- spring mvc接收JSON格式的参数
1.配置spring解析json的库 <dependency> <groupId>org.codehaus.jackson</groupId> ...
- Spring MVC(六)--通过URL传递参数
URL传递参数时,格式是类似这样的,/param/urlParam/4/test,其中4和test都是参数,这就是所谓的Restful风格,Spring MVC中通过注解@RequestMapping ...
- Spring mvc 下Ajax获取JSON对象问题 406错误
我在学习springmvc过程中(我的项目是配置的后缀是.html),从controller返回对象. 如果我不使用 mvc-annotation-driver,而是手动配置,AnnotationMe ...
随机推荐
- c语言中字符串转数字的函数
ANSI C 规范定义了 atof().atoi().atol().strtod().strtol().strtoul() 共6个可以将字符串转换为数字的函数,大家可以对比学习.另外在 C99 / C ...
- vue的组件名称问题
如果组件名称中带有大写字母,那么会报错
- Kafka消息丢失
1.Kafka消息丢失的情况: (1)auto.commit.enable=true,消费端自动提交offersets设置为true,当消费者拉到消息之后,还没有处理完 commit interval ...
- C# 接收C++ dll 可变长字节或者 字符指针 char*
网络上查找到的几乎都是 需要提前固定知道 接收字符(字节)数据的大小的方式,现在的数据大小方式 不需要提前知道如下 思路: 1 .C++,返回变长 指针或者字节 的地址给C# 接收,同时返回 该地址的 ...
- mysqldump 原理(转载)
mysqldump 备份过程可以描述为: (1) 先发出一条 flush tables 关闭实例上所有打开的表(2) 创建一个全局锁,FLUSH TABLES WITH READ LOCK获得 db ...
- VS - Paginated
BootstrapPagination.cshtml @model PaginationModel <div class="pagination"> <ul> ...
- XAMPP环境搭建WordPress,DVWA
本周学习内容: 1.学习MySQL数据库.Linux.PHP开发: 2.复习等级培训内容: 3.使用xampp环境安装WordPress,学习WordPress数据库表的设计: 4.使用xampp安装 ...
- bzoj 1100: [POI2007]对称轴osi 思维
特别神的一道题. 有一句话要反复揣摩:题中给的所有点构成一个多边形!! 而且读入还是按照多边形的轮廓读进来的!!! 我们知道,如果对称轴确定的话判定条件是对应角相等且对应边相等. 所以把相邻边夹角和边 ...
- ES code study
pom.xml <?xml version="1.0" encoding="UTF-8"?><project xmlns="http ...
- BZOJ 1857: [Scoi2010]传送带
二次联通门 : BZOJ 1857: [Scoi2010]传送带 /* BZOJ 1857: [Scoi2010]传送带 三分套三分 可能是吧..dalao们都说明显是一个单峰函数 可是我证不出来.. ...