SpringMVC之注解RequestParam、RequestBody

一、RequestParam

1.springmvc 方法中的注解RequestParam

1
@RequestMapping("/remove.sdo")
public void remove(HttpServletResponse response, @RequestParam(value = "adOrder") String adOrder)

2
@RequestMapping("/remove.sdo")
public void remove(HttpServletResponse response, @RequestParam(value = "adOrder", required = false) String adOrder)

3
@RequestMapping("/remove.sdo")
public void remove(HttpServletResponse response, String adOrder)

 

 

第一种当请求方法中没有adOrder的时候回报错,其实相当于@RequestParam(value = "adOrder", required = true)

2.第二种与第三种相同,如果参数类型是非基本类型 不会报错,会将null值赋值给方法中指定的变量,如果是基本类型int ,long会报错,

 

Optional int parameter 'notIncludeTypeId' is not present 
but cannot be translated into a null value due to being declared as a primitive type. 
Consider declaring it as object wrapper for the corresponding primitive type.


当可选参数“notIncludeTypeId”不存在时,spring默认将其赋值为null,但由于notIncludeTypeId已定于为基本类型int,所以赋值失败!
解决办法 int 改成包装类型Integer

3.请求样例

请求工具为:postman

二、RequestBody

1.@RequestBody注解可以接收json格式的数据,并将其转换成对应的数据类型。

2.处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。application/json、application/xml等格式的数据,必须使用@RequestBody来处理。

3.GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。@RequestBody用于post请求,不能用于get请求
4.POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。

 

需要注意:

1).数据应放在http body中;

2).content-type=application/json;

3).如果Controller 中RequestBody注解的参数是一个对象body={},如果RequestBody注解的参数是一个list的集合,应该是json数组body=[{},{}]

接受者为单个对象

@RequestMapping(value = "/loanMq/one_body", method = RequestMethod.POST)
public JsonResult testBatcgLoanMq(@RequestBody QueueMsg queueMsgs){
...
}

接受者为list

@RequestMapping(value = "/loanMq/batch", method = RequestMethod.POST)
public JsonResult testBatcgLoanMq(@RequestBody List<QueueMsg> queueMsgs){
...
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值