@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
推荐阅读
- 操作系统|[译]从内部了解现代浏览器(1)
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- web网页模板|如此优秀的JS轮播图,写完老师都沉默了
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- JavaScript|vue 基于axios封装request接口请求——request.js文件
- vue.js|vue中使用axios封装成request使用