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",截图如下:

  • 相关阅读:
    Day 20 初识面向对象
    Day 16 常用模块
    Day 15 正则表达式 re模块
    D14 模块 导入模块 开发目录规范
    Day 13 迭代器,生成器,内置函数
    Day 12 递归,二分算法,推导式,匿名函数
    Day 11 闭包函数.装饰器
    D10 函数(二) 嵌套,命名空间作用域
    D09 函数(一) 返回值,参数
    Day 07 Day08 字符编码与文件处理
  • 原文地址:https://www.cnblogs.com/linjiaxin/p/9297833.html
Copyright © 2011-2022 走看看