@RequestParam 的使用

@RequestParam 的使用

​ 之前帖子https://blog.csdn.net/renhuan28/article/details/80507058里写了些@requestbody 的使用,如果ajax里只要想controller里传一个String参数,使用@requestbody 要不需要用一个实体类交互,要不需要对用String接到了json格式进行次转换,而用@RequestParam 可以直接映射接到数据,但是有一些细节上的坑,导致经常会出现 Required Integer parameter 'studentId' is not present 的异常。

controller层:

 @PostMapping(value = "/updateStudent")
  public String updateStudentByStudentId(
      @RequestParam(value = "studentId") Integer studentId,
      @RequestParam(value = "name") String name) {
    try {
      studentServerce.updateStudentByStudentId(studentId, name);
    } catch (SQLException e) {
      return e.toString();
    }
    return "ok";
  }

js ajax里:

function updateStudent() {
    $("#update-student").bind('click', function () {
      if (!confirm("确认更改此配置吗")) {
        return;
      }
      var studentId = $(this).attr("studentId");
      var name = $("#student-name").val();
      $.ajax({
        type: "post",
        dataType: "text",
        contentType: "application/x-www-form-urlencoded",
        traditional: true, //traditional 为true阻止深度序列化
        url: "/student/updateStudent",
        async: false,
        data: {
          "studentId": studentId,
          "name": name
        },
        success: function (res) {
          notie.alert({
            type: 4,
            text: res,
            stay: false,
            time: 3,
            position: "top"
          })
        },
        error: function () {
          notie.alert({
            type: 3,
            text: "回调失败",
            stay: false,
            time: 3,
            position: "top"
          })
        }
      })
    });
  }
关键要注意的属性:
   contentType: "application/x-www-form-urlencoded",
   traditional: true, //traditional 为true阻止深度序列化
   data: {
          "studentId": studentId,
          "name": name
         },
  • 默认的话,traditional为false,即jquery会深度序列化参数对象,而导致@RequestParam无法正常映射
  • @requestbody 一般处理的都是非Content-Type: application/x-www-form-urlencoded编码格式的数据,而@RequestParam 的contentType为application/x-www-form-urlencoded,RequestParam 不能接受json的,但表单的可以

备注:

​ @RequestParam有三个属性,分别如下:

​ (1) value 请求参数的参数名,作为参数映射名称;
​ (2) required 该参数是否必填,默认为true(必填),当设置成必填时,如果没有传入参数,报错;
​ (3) defaultValue 设置请求参数的默认值;

本文地址:https://blog.csdn.net/renhuan28/article/details/81841062

  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值