【问题标题】:How to get context path in thymelaef如何在百里香中获取上下文路径
【发布时间】:2018-03-15 12:42:10
【问题描述】:

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

编辑:&lt;td&gt;&lt;a th:href="@{/}+${ 'user/' + user.id}"&gt;View&lt;/a&gt;&lt;/td&gt;修复

还有其他解决方案吗?

【问题讨论】:

    标签: javascript spring-boot thymeleaf


    【解决方案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>
    

    【讨论】:

      【解决方案2】:

      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>
      

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

      【讨论】:

      • 我将 Web 应用程序部署为 Tomcat 上的 war 文件,并使用 context.xml 文件设置上下文路径。当我将路径值从 更改为 时,href 值不会改变。
      猜你喜欢
      • 2018-09-12
      • 2014-06-03
      • 2019-08-10
      • 2017-10-21
      • 2018-04-25
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多