@RequestParam、@RequestBody和@ModelAttribute区别
一、@RequestParam
GET和POST请求传的参数会自动转换赋值到@RequestParam 所注解的变量上
1. @RequestParam(org.springframework.web.bind.annotation.RequestParam)用于将指定的请求参数赋值给方法中的形参。
例:
(1) get请求:
url请求:http://localhost:8080/WxProgram/findAllBookByTag?tagId=1&pageIndex=3
userTest.jsp
<form action="/WxProgram/json/requestParamTest" method="get">
requestParam Test<br>
用户名:<input type="text" name="username"><br>
用户昵称:<input type="text" name="usernick"><br>
<input type="submit" value="提交">
</form>
UserController.java
@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
public String requestParamTest(@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick){
System.out.println("requestParam Test");
System.out.println("username: " + userName);
System.out.println("usernick: " + userNick);
return "hello";
}
上述代码会将请求中的username参数的值赋给username变量。
等价于:
@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
public String requestParamTest(String username, HttpServletRequest request){
System.out.println("requestParam Test");
System.out.println("username: " + username);
String usernick = request.getParameter("usernick");
System.out.println("usernick: " + usernick);
return "hello";
}
也可以不使用@RequestParam,直接接收,此时要求controller方法中的参数名称要跟form中name名称一致
@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
public String requestParamTest(String username, String usernick){
System.out.println("requestParam Test");
System.out.println("username: " + username);
System.out.println("usernick: " + usernick);
return "hello";
}
总结:
接收请求参数的方式:
@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick //value中的参数名称要跟name中参数名称一致
String username, String usernick// 此时要参数名称一致
HttpServletRequest request //request.getParameter("usernick")
(2) post请求:
跟get请求格式一样,只是把方法中的get换成post
@RequestParam
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
RequestParam实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。
get方式中query String的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。
二. @RequestBody
@RequestBody注解可以接收json格式的数据,并将其转换成对应的数据类型。
1. @RequestBody接收一个对象
url请求:http://localhost:8080/WxProgram/findBookByName
@RequestMapping(value="/findBookByName", method = RequestMethod.POST)
@ResponseBody
public DbBook findBookByName(@RequestBody DbBook book){
System.out.println("book: " + book.toString());
System.out.println("book name: " + book.getTitle());
String bookName = book.getTitle();
DbBook book = wxService.findBookByName(bookName);
return book;
}
2. @RequestBody接收不同的字符串
(1)前台界面,这里以小程序为例
wx.request({
url: host.host + `/WxProgram/deleteBookById`,
method: 'POST',
data: {
nick: this.data.userInfo.nickName,
bookIds: bookIds
},
success: (res) => {
console.log(res);
this.getCollectionListFn();
},
fail: (err) => {
console.log(err);
}
})
(2)controller
@RequestMapping(value="/deleteBookById",method=RequestMethod.POST)
@ResponseBody
public void deleteBookById(@RequestBody Map<String, String> map){
String bookIds = map.get("bookIds");
String nick = map.get("nick");
String[] idArray = bookIds.split(",");
Integer userId = wxService.findIdByNick(nick);
for(String id : idArray){
Integer bookid = Integer.parseInt(id);
System.out.println("bookid: " + bookid);
wxService.removeBookById(bookid, userId);
}
}
@RequestBody
处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。
GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。
@RequestBody用于post请求,不能用于get请求
这里涉及到使用@RequestBody接收不同的对象
1. 创建一个新的entity,将两个entity都进去。这是最简单的,但是不够“优雅”。
2. 用Map<String, Object>接受request body,自己反序列化到各个entity中。
3. 类似方法2,不过更为generic,实现自己的HandlerMethodArgumentResolver。参考这里
三、@ModelAttribute
@ModelAttribute注解类型将参数绑定到Model对象
1. userTest.jsp
<form action="/WxProgram/json/modelAttributeTest" method="post">
modelAttribute Test<br>
用户id:<input type="text" name="userId"><br>
用户名:<input type="text" name="userName"><br>
用户密码:<input type="password" name="userPwd"><br>
<input type="submit" value="提交"><br>
</form>
name的属性值要跟User的属性相对应。
2. UserController.java
@RequestMapping(value="/modelAttributeTest", method = RequestMethod.POST)
public String modelAttributeTest(@ModelAttribute User user){
System.out.println("modelAttribute Test");
System.out.println("userid: " + user.getUserId());
System.out.println("username: " + user.getUserName());
System.out.println("userpwd: " + user.getUserPwd());
return "hello";
}
3. User.java
public class User {
private Integer userId;
private String userName;
private String userPwd;
public User(){
super();
}
//setter and getter
}
当前台界面使用GET或POST方式提交数据时,数据编码格式由请求头的ContentType指定。分为以下几种情况:
1. application/x-www-form-urlencoded,这种情况的数据@RequestParam、@ModelAttribute可以处理,@RequestBody也可以处理。
2. multipart/form-data,@RequestBody不能处理这种格式的数据。(form表单里面有文件上传时,必须要指定enctype属性值为multipart/form-data,意思是以二进制流的形式传输文件。)
3. application/json、application/xml等格式的数据,必须使用@RequestBody来处理。
参考:
https://segmentfault.com/q/1010000009017635
@RequestParam、@RequestBody和@ModelAttribute区别的更多相关文章
- Spring @RequestParam、@RequestBody和@ModelAttribute区别
一.@RequestParamGET和POST请求传的参数会自动转换赋值到@RequestParam 所注解的变量上1. @RequestParam(org.springframework.web.b ...
- SpringMVC传参注解@RequestParam,@RequestBody,@ResponseBody,@ModelAttribute
参考文档:https://blog.csdn.net/walkerjong/article/details/7946109 https://www.cnblogs.com/daimajun/p/715 ...
- @PathVariable @RequestParam @RequestBody 的区别
转载自:@RequestParam @RequestBody @PathVariable 等参数绑定注解详解 简介: handler method 参数绑定常用的注解,我们根据他们处理的Request ...
- Spring MVC之@RequestParam @RequestBody @RequestHeader 等详解
(转自:http://blog.csdn.net/walkerjong/article/details/7946109#) 引言: 接上一篇文章,对@RequestMapping进行地址映射讲解之后, ...
- @RequestParam @RequestBody @PathVariable 等参数绑定注解详解
文章主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用. 简介: handler method 参数绑定常用的注解,我们根据他们处理的Request ...
- 《转载》Spring MVC之@RequestParam @RequestBody @RequestHeader 等详解
引言: 接上一篇文章,对@RequestMapping进行地址映射讲解之后,该篇主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用: 简介: han ...
- 11.@RequestParam @RequestBody @PathVariable 等参数绑定注解详解
对@RequestMapping进行地址映射讲解之后,该篇主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用: 简介: handler method ...
- @RequestParam @RequestBody @PathVariable 等参数绑定注解详解(转)
引言: 接上一篇文章,对@RequestMapping进行地址映射讲解之后,该篇主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用: 简介: han ...
- SpringMVC之@RequestParam @RequestBody @RequestHeader 等详解
转自:http://blog.csdn.net/kobejayandy/article/details/12690161?reload 简介: handler method 参数绑定常用的注解,我们根 ...
随机推荐
- 坑:微信小程序wx.request和wx.uploadFile中传参数的区别
微信小程序中通过组件<form>提交表单的时候,在js中通过e.detail.value得到所提交表单的json格式数据.一般提交表单我们都是通过wx.request请求,提交表单数据,通 ...
- Dynamics Customer Engagement V9版本配置面向Internet的部署时候下一步按钮不可点击的解决办法
微软动态CRM专家罗勇 ,回复299或者20190120可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . Dynamics 3 ...
- Linux下创建桌面快捷方式
建立一个文本文件,文件名必须以.desktop结尾,.desktop前面的作为快捷方式的名称 添加如下内容 [Desktop Entry]Encoding=UTF-8Name=PostmanExec= ...
- SQL Server 迁移至MySQL 关键步骤的梳理总结
迁移主要是通过Navicat工具来实现的.迁移工具的选定在此不讨论. 迁移前准备 1.提前通知DBA\SA\BI等,并确认发布计划及数据库迁移方案. 2.梳理出SQL Server DB 中影响业务 ...
- 如何在MongoDB设计存储你的数据(JSON化)?
第一步 定义要描述的数据集 当我们决定将数据存储下来的时候,我们首先要回答的一个问题就是:“我打算存储什么样的数据?这些数据之间有什么关系?实体之间有什么关系?实体的属性之间有什么关系”. 为了说明问 ...
- git 初探
1,创建GIT代码仓库 git init 2,添加修改到缓存区 git add filename 3,提交缓存区的修改 git commit -m "任意文字(便于自己记忆)" 4 ...
- nginx日志切割(logrotate或shell脚本)
nginx自己不会对日志文件进行切割,可以通过两种不同的方式进行,分别是:通过logrotate和通过shell脚本. 如果是yum方式安装的nginx,系统默认会自动通过logrotate这个日志管 ...
- final等关键字和代码块
一.final关键字 其作用 1.final除构造方法外均可修饰 2.修饰类:被final修饰的类是无法被继承的. 3.修饰方法,可被继承,但是无法被重写 4.修饰变量使其为常量 5.修饰引用型变量, ...
- react组件之间的通信
通过props传递 共同的数据放在父组件上, 特有的数据放在自己组件内部(state),通过props可以传递一般数据和函数数据, 只能一层一层传递 一般数据-->父组件传递数据给子组件--&g ...
- 外部访问docker中的MySQL
注:192.168.1.203机器上装有docker,容器在该机器上 mysql> use mysql; mysql> update user set authentication_str ...