Spring Boot对接HTML表单报错:HttpMediaTypeNotSupportedException如何解决?
解决Spring Boot表单提交的HttpMediaTypeNotSupportedException异常
问题现象
提交HTML表单时触发如下异常:
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported]
问题根源
控制器中使用@RequestBody注解接收表单数据,但@RequestBody默认用于解析JSON/XML格式的请求体,无法直接处理application/x-www-form-urlencoded类型的表单参数。即便指定了consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,Spring也不会自动将表单参数绑定到实体类对象。
修复方案
两种方式任选其一即可:
方式一:替换@RequestBody为@ModelAttribute
修改控制器方法参数,将@RequestBody换成@ModelAttribute,Spring会自动完成表单参数到实体类的映射:
@PostMapping(value="/register", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ResponseEntity<signUp> registerUser(@ModelAttribute signUp signUp){ signUp registeredUser = ModelService.registerUser(signUp); return ResponseEntity.ok(registeredUser); }
方式二:改用JSON格式提交表单(适合前后端分离场景)
若要保留@RequestBody,可通过JavaScript将表单数据转为JSON格式提交:
- 修改HTML表单,移除
enctype并添加ID便于JS操作:
<form method="post" id="signupForm"> <div class="signuppage"> <label for="firstName"><b>First Name</b></label> <input type="text" placeholder="Enter First Name" name="firstName" required><br> <label for="lastName"><b>Last Name</b></label> <input type="text" placeholder="Enter Last Name" name="lastName" required><br> <label for="email"><b>Email</b></label> <input type="text" placeholder="Enter email" name="email" required><br> <label for="password"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required><br> <button type="submit">Sign Up</button> </div> </form>
- 添加JavaScript处理表单提交逻辑:
document.getElementById('signupForm').addEventListener('submit', function(e) { e.preventDefault(); const formData = new FormData(this); const data = Object.fromEntries(formData.entries()); fetch('/signup/register', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => { console.log('注册成功:', result); // 可添加成功后的跳转或提示逻辑 }) .catch(error => { console.error('注册失败:', error); }); });
- 修改控制器,去掉
consumes配置,默认支持JSON格式:
@PostMapping(value="/register") public ResponseEntity<signUp> registerUser(@RequestBody signUp signUp){ signUp registeredUser = ModelService.registerUser(signUp); return ResponseEntity.ok(registeredUser); }
额外编码规范优化建议
- 实体类名
signUp不符合Java大驼峰命名规范,建议改为SignUp - 控制器、服务类中的变量名
ModelService、ModelRepository建议改为小驼峰modelService、modelRepository
内容的提问来源于stack exchange,提问作者Muhammed Mufeed
相关产品推荐
相关产品推荐

