You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot整合Thymeleaf如何实现表单POST提交JSON格式数据

问题原因

原生HTML表单默认的提交编码格式是application/x-www-form-urlencoded(文件上传时为multipart/form-data),属于form-data结构,而Spring Boot的@RequestBody注解默认只会解析Content-Type为application/json的请求体,二者格式不匹配,因此无法直接完成参数绑定。
你可以根据自身业务场景选择以下两种方案解决:


方案1:调整后端接口适配表单提交(改动最小,推荐Thymeleaf服务端渲染场景使用)

直接移除接口参数上的@RequestBody注解,Spring MVC会自动按照form-data格式将请求参数绑定到DTO对象上,还能无缝兼容Thymeleaf自带的字段绑定、校验错误回显能力。
调整后的Controller代码示例:

@PostMapping(value = "/save-new-password")
public String saveStudent(@Valid NewPasswordDTO newPasswordDTO, BindingResult bindingResult) {
    // 校验参数不通过时直接返回重置页,可配合th:errors展示错误提示
    if (bindingResult.hasErrors()) {
        return "reset-password-page";
    }
    // 编写密码重置的业务逻辑
    return "redirect:/password-reset-success";
}
  • 注意:BindingResult参数必须紧跟在被@Valid修饰的参数后面,否则校验失败时会直接抛出400错误,无法走自定义的错误处理逻辑。

方案2:调整前端提交逻辑适配JSON接口(适合接口需要多端复用的场景)

如果你的/save-new-password接口还要给APP、小程序等其他客户端提供服务,必须保留@RequestBody接收JSON,可以通过前端JS拦截表单默认提交行为,将表单数据序列化为JSON格式后再发送请求。
调整后的页面代码示例:

<body>
    <!-- 给表单加id方便JS获取 -->
    <form id="resetPwdForm" th:action="@{/save-new-password}" th:object="${newPasswordDTO}" method="post">
        <div class="box">
            <h1>RESET PASSWORD</h1>
            <input class="password" name="newPassword" type="password" placeholder="New password" th:field="*{newPassword}">
            <input class="password" name="confirmPassword" type="password" placeholder="Confirm password" th:field="*{confirmPassword}">
            <input class="button" type="submit" value="RESET"/>
        </div>
    </form>

    <script>
        const form = document.getElementById('resetPwdForm');
        form.addEventListener('submit', async function(e) {
            // 阻止表单默认的form-data提交行为
            e.preventDefault();
            // 收集表单字段转为普通JS对象
            const formData = new FormData(form);
            const jsonPayload = Object.fromEntries(formData.entries());
            // 发送JSON格式请求
            const response = await fetch(form.action, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(jsonPayload)
            });

            if (response.ok) {
                // 提交成功后跳转至成功页
                window.location.href = '/password-reset-success';
            } else {
                // 自定义错误提示逻辑
                alert('密码重置失败,请确认两次输入的密码一致且符合规则');
            }
        })
    </script>
</body>
  • 注意:该方案属于异步提交,无法直接使用Thymeleaf默认的服务端校验回显能力,需要自行处理接口返回的错误信息并渲染到页面。

内容的提问来源于stack exchange,提问作者Adam Barča

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 05:24:23