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

Thymeleaf如何用window.location.origin替换链接中的REDIRECT参数

解决Thymeleaf中替换链接参数为window.location.origin的问题

你之前的写法无效,核心原因是Thymeleaf是服务端渲染引擎——页面发送到浏览器前就完成了解析,根本无法执行浏览器端的JavaScript函数,所以javascript:getDomain();只会被当作字面量字符串填充到链接里。

下面提供两种可行的解决方案:

方案一:前端JS动态修改链接(推荐)

先通过Thymeleaf渲染出配置中的原始链接,再用JS在页面加载时替换占位符或调整参数:

  1. Thymeleaf代码(渲染原始链接,保留{REDIRECT}占位符):
<a id="pwdResetLink" th:href="${@environment.getProperty('MY_PWD_RESET_LINK')}">重置密码</a>
  1. JavaScript代码(页面加载后替换参数):
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  const resetLink = document.getElementById('pwdResetLink');
  const currentOrigin = window.location.origin;
  
  // 方法1:直接替换链接中的{REDIRECT}占位符
  let updatedHref = resetLink.href.replace('{REDIRECT}', encodeURIComponent(currentOrigin));
  
  // 方法2:移除原redirect参数后追加新值(可选,适用于严格管理参数的场景)
  // const url = new URL(resetLink.href);
  // url.searchParams.delete('redirect');
  // url.searchParams.append('redirect', encodeURIComponent(currentOrigin));
  // updatedHref = url.toString();
  
  resetLink.href = updatedHref;
});

方案二:服务端接收前端传递的origin后替换(适合必须服务端处理的场景)

如果一定要在服务端完成替换,需要前端先将window.location.origin传递给后端,再通过Thymeleaf渲染:

  1. 前端请求页面时携带origin参数(比如通过URL参数):
// 跳转重置页面时携带origin
window.location.href = '/reset-page?origin=' + encodeURIComponent(window.location.origin);
  1. 后端(以Spring Boot为例)接收参数并存入Model:
@GetMapping("/reset-page")
public String showResetPage(@RequestParam String origin, Model model) {
  model.addAttribute("currentOrigin", origin);
  return "reset"; // 对应Thymeleaf模板名称
}
  1. Thymeleaf代码替换参数:
<a th:href="@{${@environment.getProperty('MY_PWD_RESET_LINK')}(REDIRECT=${currentOrigin})}">重置密码</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:23:26