我使用 Thymeleaf 模板开发 Spring Boot 应用程序。我想在下面的代码中添加前缀(服务器上下文路径),例如
'serverContext/user/' + user.id
。我尝试将 $ 更改为 @ 但 user.id
已转换为字符串。
谢谢你。
<tr th:each="user : ${users}">
<td><a th:href="${ '/user/' + user.id}">View</a></td>
</tr>
编辑:由
<td><a th:href="@{/}+${ 'user/' + user.id}">View</a></td>
修复
还有其他解决办法吗?
在 application.properties:
server.context-path=/test
服务等级:
@Component("helperService")
public class HelperService {
@Value("${server.context-path}")
private String contextPath;
public String getContextPath(){
return contextPath;
}
}
Html 文件:
<span th:text="${@helperService.getContextPath()}"></span>
mrt的答案有效,但提供了一个不必要的额外bean。
只需注入 ServerProperties
并调用
getContextPath()
。此 bean 作为
@ConfigurationProperties
提供,因此已经可用。请参阅服务器属性。
但是这解决了您的要求,但是如果您不使用绝对路径,您的问题就不会成为问题。为什么不使用这样的相对路径:
<td><a th:href="${ 'user/' + user.id}">View</a></td>
假设您位于
$host$/serverContext
$host$/serverContext/someOtherPath
并想要链接到您的用户页面,则可以使用以下方法:
<td><a th:href="${ '../user/' + user.id}">View</a></td>
等等。不需要知道这个的上下文路径。
Thymeleaf 3.1.2、Spring Boot 3.1.3 和 Java 17 进行了此配置:
生成Service“LocalService.java”,用@Component注释
@Component("localService")
public class LocalService {
@Autowired
private ServletContext context;
public String getContextPath() {
return this.context.getContextPath();
}
}
在 HTML 中,Thymeleaf 通过 @localService: 获取服务
<div th:content="${@localService.getContextPath()}"></div>