zoukankan      html  css  js  c++  java
  • 使用与不使用@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",截图如下:

  • 相关阅读:
    LibreOJ 6003. 「网络流 24 题」魔术球 贪心或者最小路径覆盖
    LibreOJ #6002. 「网络流 24 题」最小路径覆盖
    LibreOJ #6000. 「网络流 24 题」搭配飞行员 最大匹配
    LibreOJ 2003. 「SDOI2017」新生舞会 基础01分数规划 最大权匹配
    hdu 1011 Starship Troopers 树形背包dp
    Codeforces Round #135 (Div. 2) D. Choosing Capital for Treeland dfs
    hdu 6199 gems gems gems dp
    hdu 5212 Code 筛法或者莫比乌斯
    hdu 3208 Integer’s Power 筛法
    hdu 5120 Intersection 两个圆的面积交
  • 原文地址:https://www.cnblogs.com/linjiaxin/p/9297833.html
Copyright © 2011-2022 走看看