使用与不使用@RequestBody注解的区别

1.
如果使用@RequestBody接受页面参数:
public Map<String,Object> insertBudget(@ApiParam(required = true,name = "actBudgetCost",value = "预算")@RequestBody ActBudgetCost actBudgetCost, HttpServletRequest request){

}

那么前台页面ajax应该这样写:
$.ajax({
        url: '',
        type: "POST",
        data: JSON.stringify({
            "actiName":name
        }),
        dataType: "json",
        contentType: "application/json",
        async: false,
        success: function (result) {

        },
        error: function (xhr, ajaxOptions, thrownError) {
            //console.log(thrownError); //alert any HTTP error
            //alert("请求出错!");
            return false;
        }
    });

2.
如果不使用@RequestBody接受页面参数:
public Map<String, Object> regProduct(HttpServletRequest request,
                                           @ApiParam(name = "customerProAuditPO", value = "产品注册实体")CustomerProAuditVO customerProAuditVO
    ) {

}

那么前台页面ajax应该这样写:
var data = {
    customerName:customerName,
};
$.ajax({
        url:'',
        type: "POST",
        data: data, 
        //async: false,
        dataType:"json",
        success: function(result) {
            var json = result;

        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            return false;
        }
    });
复制代码

一、问题描述

      由于项目是前后端分离,因此后台使用的是spring boot,做成微服务,只暴露接口。接口设计风格为restful的风格,在get请求下,后台接收参数的注解为RequestBody时会报错;在post请求下,后台接收参数的注解为RequestParam时也会报错。

二、问题原因

     由于spring的RequestParam注解接收的参数是来自于requestHeader中,即请求头,也就是在url中,格式为xxx?username=123&password=456,而RequestBody注解接收的参数则是来自于requestBody中,即请求体中。

三、解决方法

      因此综上所述,如果为get请求时,后台接收参数的注解应该为RequestParam,如果为post请求时,则后台接收参数的注解就是为RequestBody。附上两个例子,截图如下:

      get请求

  

post请求

 

        另外,还有一种应用场景,接口规范为resultful风格时,举个例子:如果要获取某个id下此条问题答案的查询次数的话,则后台就需要动态获取参数,其注解为@PathVariable,并且requestMapping中的value应为value="/{id}/queryNum",截图如下:

 

posted @ 2018-07-12 09:25  林加欣  阅读(32882)  评论(0编辑  收藏  举报