理论上传过来的数据是
{
“newPassword”: “123”,
“oldPassword”: “123”
}
但是如果把controller写成这样的话
@ApiOperation("修改密码")@PutMapping("/password/{id}")public Account editPassword(@PathVariable(value = "id") Long id,String oldPassword,String newPassword){return accountService.edit(id,oldPassword,newPassword);}
前端会报错,用swagger测试的时候发现,看浏览器的请求里面是这样的:
正确的应该是这样的
然后用postman测试的话也会报错.
观察了对比的差异,发现后台把参数全部拼写在路径里面了.类似get请求那样,查了很多资料都不知道要怎么处理.最后还是从项目中找到了之前的做法,就是把json的两个字段用一个对象来封装起来,然后加上注解@RequestBody就可以了
具体如下:
@ApiOperation("修改密码")@PutMapping("/password/{id}")public Account editPassword(@ApiParam(value = "用户id", required = true) @PathVariable(value = "id") Long id,@RequestBody AccountPassword accountPassword){return accountService.edit(id,accountPassword);}//封装类
public class AccountPassword {private String oldPassword;private String newPassword;public String getOldPassword() {return oldPassword;}public void setOldPassword(String oldPassword) {this.oldPassword = oldPassword;}public String getNewPassword() {return newPassword;}public void setNewPassword(String newPassword) {this.newPassword = newPassword;}
}
结论
要同时传路径变量和json的做法就是:
@PathVariable+@RequestBody