如何在thymelaef中获取上下文路径

问题描述 投票:0回答:3

我使用 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>

修复

还有其他解决办法吗?

javascript spring-boot thymeleaf
3个回答
1
投票

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>

0
投票

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>

等等。不需要知道这个的上下文路径。


0
投票
我对

Thymeleaf 3.1.2Spring Boot 3.1.3Java 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>
    
© www.soinside.com 2019 - 2024. All rights reserved.