如何使用Thymeleaf获取变量值并生成正确URL
解决Thymeleaf URL变量解析问题
嘿,我明白你为啥碰到这个麻烦啦!你现在的写法里,直接在普通的href属性里写${user.getToken()},Thymeleaf压根不会解析这个表达式——浏览器只会把它当成普通字符串进行URL编码,所以才会出现$%7Buser.getToken()%7D这种转义后的奇怪内容。
要让Thymeleaf正确解析变量生成动态URL,你得用它专属的th:href属性,下面给你两种可行的写法:
方法一:使用Thymeleaf URL语法(推荐)
这种写法会自动处理应用上下文路径,适配不同部署场景,更灵活:
<div th:if="${!user.isEmailValidated()}" class="div-block-13"> <div class="email_confirmed"> <a th:href="@{/email/send/{token}(token=${user.token})}">Your email is not confirmed!</a> </div> </div>
这里的@{/email/send/{token}}是URL模板,(token=${user.token})用来给模板里的{token}占位符赋值。另外Thymeleaf支持直接用user.token代替user.getToken(),它会自动调用对应的getter方法,写法更简洁。
方法二:字符串拼接写法
如果觉得URL语法有点绕,也可以直接用字符串拼接:
<div th:if="${!user.isEmailValidated()}" class="div-block-13"> <div class="email_confirmed"> <a th:href="'/email/send/' + ${user.token}">Your email is not confirmed!</a> </div> </div>
你的Spring控制器代码是完全没问题的,只要Thymeleaf生成了正确的动态URL,就能成功匹配到@GetMapping("/email/send/{token}")这个接口啦。
内容的提问来源于stack exchange,提问作者Georgi Michev
相关产品推荐
相关产品推荐

