java|@RequestParam 的使用

@RequestParam 的使用
【java|@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 = "https://www.it610.com/updateStudent") public String updateStudentByStudentId( @RequestParam(value = "https://www.it610.com/article/studentId") Integer studentId, @RequestParam(value = "https://www.it610.com/article/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

    推荐阅读