如何获得百里香的背景路径

时间:2017-10-04 07:39:25

标签: javascript spring-boot thymeleaf

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

修复

还有其他解决方案吗?

2 个答案:

答案 0 :(得分:0)

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>

答案 1 :(得分:0)

mrt的答案有效,但提供了一个不必要的额外bean。 只需注入ServerProperties并致电getContextPath()

此bean以@ConfigurationProperties提供,因此已经可用。请参阅ServerProperties

这解决了您的要求,但如果您不使用绝对路径,则问题不会成为问题。为什么不使用这样的相对路径:

<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>

等等。没有必要知道这个的上下文路径。