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

Spring Boot结合Thymeleaf时,表单提交后重定向到模板页面出现404错误

Spring Boot结合Thymeleaf时,表单提交后重定向到模板页面出现404错误

这个问题我之前也碰到过,核心原因是Spring Boot对静态资源和Thymeleaf模板的请求处理优先级导致的,咱们一步步理清楚:

问题根源

你的index.html放在src/main/resources/templates/下,这是Thymeleaf的专属模板目录,需要通过控制器映射来渲染。但你重定向的目标是/index.html,Spring Boot默认会把.html结尾的请求优先交给静态资源处理器处理——它会去src/main/resources/static/目录下找对应的静态文件,而你的index.html不在这个目录里,所以自然返回404。哪怕你写了@GetMapping("/index.html"),静态资源处理器的优先级也比控制器映射高,导致这个方法根本没被触发。

快速解决方案

调整重定向路径和控制器映射,去掉.html后缀,用逻辑路径来访问模板:

  1. 修改authenticateWithQr方法的重定向目标:
@GetMapping("/authenticate/qr")
public String authenticateWithQr(@RequestParam("qrCode") String qrCode, HttpServletResponse response, RedirectAttributes redirectAttributes) {
    if (StringUtils.isBlank(qrCode)) {
        return "redirect:/index"; // 去掉.html后缀
    }
    final TokenResult tokenResult = authenticateApi.generateToken(qrCode);
    redirectAttributes.addFlashAttribute("request_number", tokenResult.getRequestNumber());
    redirectAttributes.addFlashAttribute("phone_number", tokenResult.getPhoneNumber());
    redirectAttributes.addFlashAttribute("amount", tokenResult.getAmount());
    redirectAttributes.addFlashAttribute("merchant_name", tokenResult.getMerchantName());
    response.setHeader("Authorization", "Bearer " + tokenResult.getToken());
    return "redirect:/index"; // 同样修改这里
}
  1. 调整showIndex方法的映射路径:
@GetMapping("/index") // 去掉.html后缀
public String showIndex() {
    return "index"; // 依然指向templates/index.html模板
}

这样重定向到/index时,请求会被控制器拦截,然后渲染Thymeleaf模板,就不会出现404了。

补充说明

  • 你之前用Model传递参数的方式不行,因为重定向是客户端跳转,Model里的属性无法跨请求传递,用RedirectAttributes的flashAttribute是正确的做法——这些属性会暂存在session中,渲染index.html时可以通过Thymeleaf表达式(比如${request_number})获取。
  • 尽量遵循Spring Boot的默认规范:静态资源放static目录,模板放templates目录,控制器映射用无后缀的逻辑路径,这样能避免很多资源匹配的坑。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 08:09:29