使用与不使用@RequestBody注解的区别及使用@RequestBody的一些问题

1.使用@RequestBody注解:

    前端ajax传送数据的时候,需要指明contentType参数为:contentType: "application/json"

    @RequestBody注解接收的参数是Json对象的字符串,所以需要用JSON.stringify()将对象转换为字符串

    否则得不到数据

    定义接口:

//后台接口:
@RequestMapping(value = "/addUnearthedAnnexRecords")
public Result addUnearthedAnnexRecords(@RequestBody UnearthedAnnexRecordsRequest unearthedAnnexRecordsRequest) {

    return Result;

}

//实体类:
@Data
public class UnearthedAnnexRecordsRequest {

    private Long mid;

    private String name;

    private String description;

}


//前端ajax请求:
$.ajax({
        url: '/addUnearthedAnnexRecords',
        type: "POST",
        data: JSON.stringify({
                "mid":mid,
                "name":name,
                "description":description
              }),
        dataType: "json",
        contentType: "application/json",

        success: function (result) {
            //do something ...
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //console.log(thrownError); //alert any HTTP error
            return false;
        }
    });

2.不使用@RequestBody注解:

    不需要特别指定contentType参数,服务端接收key-value形式参数

    定义接口:

//后台接口:
@RequestMapping(value = "/addUnearthedAnnexRecords")
public Result addUnearthedAnnexRecords(UnearthedAnnexRecordsRequest unearthedAnnexRecordsRequest) {

    return Result;

}

//实体类:
@Data
public class UnearthedAnnexRecordsRequest {

    private Long mid;

    private String name;

    private String description;

}


//前端ajax请求:
$.ajax({
        url: '/addUnearthedAnnexRecords',
        type: "POST",
        data: {
                "mid":mid,
                "name":name,
                "description":description
                },
        dataType: "json",
        //contentType: "application/json",
        success: function (result) {
            //do something ...
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //console.log(thrownError); //alert any HTTP error
            return false;
        }
    });

 

需要注意的问题:

即便没有特别限制请求类型,但是在使用@RequestBody注解的时候,通过Get方式请求接口,会报错,原因是因为格式类型为:xxx?mid=xx&name=xxx&description=xxx

即便是Post请求,也需要在Header里面指定contentType=application/json

我想,在接口测试的时候可能会遇到该问题。

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值