SpringMVC如何接收application/json内容编码类型的参数?

  在上代码之前,有必要先说说@ResquestBody注解的含义:

  1、官方解释如下:

Annotation indicating a method parameter 
should be bound to the body of the web request.
The body of the request is passed through an {@link HttpMessageConverter}
to resolve the method argument depending on the content type of the request.
意思大概是:用该注解标识的方法的参数,会和web请求体绑定。
http消息转换器会根据content-type的设置将请求体解析,从而初始化该方法的参数。

  2、另外还需解释一下使用的场景

GET、POST方式提交的请求:

Content-type:

1、application/x-www-form-urlencoded:@RequestBody不是必须加的

2、mutipart/form-data:@RequestBody不能处理这种格式

3、其他格式,比如application/json,application/xml等,必须使用@RequestBody来处理

PUT方式提交的请求:

以上1和3的场景都是必须使用@RequestBody来处理的,2场景也是不支持的

  3、前端代码如下:(这里必须将JSON对象使用JSON.stringify()转为JSON字符串再传递,否则后台接收不到值)

$.ajax({
    url:"../../Notice/LoadForm.do",
    type:"post",
    contentType:"application/json;charset=UTF-8",
    data:JSON.stringify({"id":"1","title":"标题"})
});

  4、后台接收代码示例

@RequestMapping(value="Notice/LoadForm")
@ResponseBody
public ResultJO loadForm(@RequestBody Notice notice){

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值