2017-10-04 61 views
0

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

是任何其他的解決辦法呢?

回答

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

釷e的mrt工作,但提供了一個額外的bean,這是沒有必要的。 只需注入ServerProperties並致電getContextPath()

此豆被提供爲@ConfigurationProperties,因此已經可用。見ServerProperties

但是這解決了你所要求的,但是如果你不使用絕對路徑,你的問題就不會成爲問題。爲什麼不使用相對pathes這樣的:

<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

我在Tomcat上將Web應用程序部署爲war文件,並使用context.xml文件設置上下文路徑。當我將路徑值從更改爲時,href值不會更改。 –