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

Thymeleaf点击按钮无法跳转至新HTML页面问题求助

问题解决:Spring+Thymeleaf中提交按钮无法跳转至CustomerLogin页面

问题说明

在Spring项目中搭配Thymeleaf框架时,点击页面内type="submit"的按钮,无法正常跳转至CustomerLogin页面。

相关代码与结构

HTML代码片段

<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Sign up Page</title>
</head>
<body>
<h1>Welcome to Getir Library</h1>
<br>
<hr>
<form th:action="@{/Main}" method="post">
  <div class = "header">
    <h1>Menu</h1>
    <button type="submit" th:onclick="|window.location.href='/CustomerLogin'|" >Customer Login Page</button>
  <!-- 省略剩余闭合标签 -->
</form>
</body>
</html>

Controller代码片段

@RequestMapping(value = "/CustomerLogin")
String getCustomerLoginPage(){
    return "CustomerLogin";
}

项目HTML文件结构

src/main/resources/templates目录下包含:

  • CustomerLogin.html
  • Main.html
  • SignUp.html
  • 其他相关页面文件

问题原因

  1. type="submit"的按钮点击后,会优先触发表单的POST提交动作(向/Main发送请求),导致onclick里的页面跳转逻辑被打断,无法执行。
  2. 直接使用window.location.href='/CustomerLogin'未采用Thymeleaf的URL表达式,若项目配置了上下文路径,会出现路径错误。

解决方案

方案1:修改按钮类型为button

将按钮的type改为button,避免触发表单提交,同时用Thymeleaf的URL表达式确保路径正确:

<button type="button" th:onclick="|window.location.href='@{/CustomerLogin}'|" >Customer Login Page</button>

方案2:用a标签替代按钮(推荐)

放弃表单提交逻辑,直接使用Thymeleaf的链接表达式实现跳转,更符合Spring MVC的设计逻辑:

<a th:href="@{/CustomerLogin}" style="display: inline-block; padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; color: #333; text-decoration: none; cursor: pointer;">Customer Login Page</a>

方案3:修改表单提交的Controller逻辑

如果必须保留表单和submit按钮,修改/Main的POST请求处理方法,让其重定向到CustomerLogin页面:

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping(value = "/Main", method = RequestMethod.POST)
public String handleMainFormSubmit() {
    return "redirect:/CustomerLogin";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 16:01:31