Spring MVC的@GetMapping方法如何接收枚举参数及提交无响应问题排查
Spring MVC枚举提交无响应问题修复方案
问题根因
- 请求方式不匹配:前端表单配置的提交方式为
POST,提交地址为/createFile,但后端仅存在两个GET类型的接口,没有对应POST接口接收请求,请求找不到对应处理逻辑因此无响应。 - 参数传递规则不匹配:后端文件生成逻辑的接口要求
vendor为URL路径变量,但前端表单提交会把参数放在请求体中,不会自动拼接至URL路径,就算请求方式匹配也无法命中对应接口。 - 拼写错误:前端标签
<lebel>拼写错误,正确为<label>;后端业务类注入字段vendorSrvice拼写错误,少了字母e,正确为vendorService。
修复方案(最简适配)
调整后端接口适配表单提交逻辑,同时修正拼写错误即可:
后端代码调整
// 原返回页面的GET接口无需修改 @GetMapping(value = "/createFile") public String selectVendor(Model model) { model.addAttribute(new Customer()); model.addAttribute("vendorType", Vendor.values()); return "vendor"; } // 新增POST接口接收表单参数,替换原路径变量GET接口 @PostMapping(value = "/createFile") public ResponseEntity selectVendor(@RequestParam("vendor") Vendor vendor) { String message = "error creating file"; // 修正业务类拼写错误 if (vendorService.createFile(vendor)) { message = "file created successfully"; } return new ResponseEntity(message, HttpStatus.OK); }
前端代码调整
仅修正标签拼写错误即可:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" th:action="@{/createFile}" th:object="${customer}"> <div> <label th:for="vendor">select Vendor</label> <select th:field="*{vendor}"> <option th:each="vendorType : ${vendorType}" th:text="${vendorType.name}" th:value="${vendorType}"> </option> </select> </div> <div style="..."><input type="submit" value="Create file"/></div> </form> </body> </html>
内容的提问来源于stack exchange,提问作者Andy Kofi
相关产品推荐
相关产品推荐

