今天使用RESTful写接口的时候发现使用put请求后端接收不到对象和参数. 网上的博客解决方式写的千篇一律却没有一个有用… 下面是我最后解决的代码, 希望能帮助到你
上代码
let _self = this;
$.ajax({
url: '/stu/account',
type: 'put',
data: {
stuUsername: _self.username, // 前端传一个对象account和一个参数newpassword
stuPassword: _self.formChPass.password,
newPassword: _self.formChPass.newpassword
},
success(data_result) {
// ...
},
error() {
// ...
}
})
后端接收参数和对象 (对象无需加@RequestBody、参数需要加@RequestParam)
详见 stackoverflow
@PutMapping("/stu/account")
public int updateMyPassword(Account account, @RequestParam String newPassword) {
// ...
}
还有另一种方式
let _self = this;
let jsondata = {
stuUsername: _self.username,
stuPassword: _self.formChPass.password
}
$.ajax({
url: '/stu/account/' + _self.formChPass.newpassword, // url中传一个参数
type: 'put',
contentType:"application/json",
data: JSON.stringify(jsondata), // data中传一个json格式的数据
success(data_result) {
// ...
},
error() {
// ...
}
})
这时候对象要用@RequestBody 来接收, 参数用@RequestParam的话接收到为null,貌似只能用@PathVariable…
@PutMapping("/stu/account/{newpassword}")
public int updateMyPassword(@RequestBody Account account, @PathVariable(value = "newpassword") String newPassword) {
// ...
}
over