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

Spring Boot实现产品创建功能提交请求返回404白标错误页如何解决

问题产生原因
  • 视图跳转失败:Controller方法返回的showInventory视图名没有对应的Thymeleaf模板文件,Spring MVC找不到对应页面触发404
  • 接口路径不匹配:Controller类如果配置了父级路由前缀,表单提交的/create_product路径和实际接口路径不一致,导致请求找不到接口
  • 配置异常:Thymeleaf视图解析器的前后缀配置错误,或者Spring Security的CSRF校验拦截了POST请求
  • 实体字段映射异常:Products实体类的product_category字段类型和表单提交的参数类型不匹配,触发异常后跳转错误页,而错误页没有配置导致返回404
排查与解决方法
  1. 核对视图文件是否存在
    到项目src/main/resources/templates目录下,确认存在showInventory.html文件,文件名大小写和Controller返回的字符串完全一致,Linux环境大小写敏感,注意不要写错大小写。
  2. 校验接口路径匹配
  • 查看当前Controller类上是否添加了@RequestMapping父级路由,比如类上配置了@RequestMapping("/product"),则实际接口路径为/product/create_product,需要将表单的th:action修改为@{/product/create_product}
  • 查看项目启动日志,确认POST /create_product接口已经被Spring成功注册
  1. 检查Thymeleaf配置
    打开application.properties或者application.yml,确认视图解析器配置正确,默认配置参考:
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
  1. Spring Security适配
    如果项目引入了Spring Security,默认开启CSRF校验,需要在表单内添加CSRF隐藏域:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

测试阶段也可以临时关闭CSRF校验排查问题:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}
  1. 日志定位
    在saveProduct方法第一行添加日志打印:
@RequestMapping(value = "/create_product",method = RequestMethod.POST)
public String saveProduct(@ModelAttribute("product") Products product) {
    // 新增日志,确认请求是否进入接口
    System.out.println("接收到产品参数:" + product);
    productService.saveProduct(product);
    return "showInventory";
}

提交表单后如果控制台有打印日志,说明请求已经进入接口,问题出在视图跳转逻辑;如果没有打印,说明请求路径错误没有匹配到接口。

内容的提问来源于stack exchange,提问作者Hesham Eldawy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:39:05