thymeleaf contextPath html javascript

由於可能你開發的contextPath 和生產的 contextPath不一樣,因此要讓你的項目能自動適應contextPath變化 。javascript

若是你是要在thymeleaf標籤中使用,有種方法能夠獲取這個值(實際上幾乎沒有能用到的地方)java

1:spa

${#httpServletRequest.getContextPath()}

2:code

${#servletContext.contextPath} 

example:server

<script th:src="|${#servletContext.contextPath}/js/index.js|"></script>

若是你沒有配置server.servlet.context-path ,那取出的值將是空字符串。blog

由於 server.servlet.context-path 的配置要求是 以 / 開始,且不能以 / 結尾。ip

因此若是你配置了,那取出來的內容 就是 /xxxx 這樣的格式,在實際使用時,下級目錄前要加 / 。開發

爲何說幾乎沒有能用到的地方, @{} 這個表達式已經能夠知足幾乎所有需求了,好比字符串

th:href get

th:src

th:onclick="|window.location.href='@{/}'|" 

 

 

 

 

若是是在js塊中引用  須要在script 標籤上加     th:inline="javascript"

而後加  CDATA 註釋   而後你的 表達式要用   /*[[  和   ]]*/  圍起來

你能夠在一個公共的頁面裏把 contextPath 聲明在js變量裏,,而後各個頁面就能夠引用這個腳本塊。

<script th:inline="javascript">
    /*<![CDATA[*/
    var $contextPath = /*[[@{/}]]*/;
    /*]]>*/
</script>
相關文章
相關標籤/搜索