Spring能否通过@RequestBody以外的方式映射POST请求参数?
Spring POST参数映射:不用@RequestBody的方式
当然可以呀!Spring完全支持不用@RequestBody来映射POST请求的参数,不过这得看前端发送请求时的参数提交格式,下面给你拆解几种常见场景:
表单格式提交(
application/x-www-form-urlencoded或multipart/form-data)
这是最常见的POST提交方式(比如普通表单上传、FormData提交),直接用@RequestParam就能映射单个参数,和GET请求的用法完全一致,就像你尝试的代码那样:@RequestMapping(value="/requestotp", method = RequestMethod.POST) public String requestOTP( @RequestParam(value="idNumber") String idNumber, @RequestParam(value="applicationType") String applicationType ) { // 处理你的OTP请求逻辑 return "OTP已发送"; }如果参数名和方法参数名完全匹配,还能简化写法——省略
@RequestParam的value属性,甚至直接不用@RequestParam(Spring会自动匹配,Spring Boot默认就支持这个特性):@RequestMapping(value="/requestotp", method = RequestMethod.POST) public String requestOTP(String idNumber, String applicationType) { // 处理逻辑 return "OTP已发送"; }用
@ModelAttribute封装参数
如果参数比较多,不想写一堆单个参数,也可以把参数封装到一个实体类里,用@ModelAttribute来接收,同样不用@RequestBody:// 定义请求参数实体类 public class OtpRequest { private String idNumber; private String applicationType; // 记得加getter和setter方法 public String getIdNumber() { return idNumber; } public void setIdNumber(String idNumber) { this.idNumber = idNumber; } public String getApplicationType() { return applicationType; } public void setApplicationType(String applicationType) { this.applicationType = applicationType; } } // 控制器方法 @RequestMapping(value="/requestotp", method = RequestMethod.POST) public String requestOTP(@ModelAttribute OtpRequest otpRequest) { String id = otpRequest.getIdNumber(); String type = otpRequest.getApplicationType(); // 处理逻辑 return "OTP已发送"; }
注意事项
如果尝试用@RequestParam却取不到参数,大概率是前端的提交格式不对——比如前端把参数放在了JSON请求体里(Content-Type: application/json),这种情况下必须用@RequestBody来接收,因为Spring无法从JSON请求体里解析出@RequestParam对应的键值对。
内容的提问来源于stack exchange,提问作者osama yaccoub
相关产品推荐
相关产品推荐

