2012-12-19 66 views
0

我想知道有沒有人可以幫忙。我們正在將Spring Webflow 2應用程序從使用基於jsp的視圖層轉換爲基於Thymeleaf的視圖。Thymeleaf可以訪問Spring servletContext嗎?

對於這個大多數情況,這是好的,但現在我正在努力讓Thymeleaf訪問我們在servletContext中放置的對象。

因此,我們有(實施ServletContextAwareInitializingBean

爲了簡單起見被放在servletContext爲bean的一部分的對象,可以說這是一個字符串:

public class ReferenceDataBuilder implements ServletContextAware, InitializingBean { 

public void setServletContext(ServletContext p_context) { 
    p_context.setAttribute("referenceData", "test text"); 
} 

在我們的基於JSP的觀點,我們可以訪問referenceData對象是這樣的:

<p><c:out value="${referenceData}"/></p> 

由MAG它知道它可以訪問的各種範圍(servletContext,flowScope,flashScope等),並且(我在猜測?)搜索每個範圍,直到找到匹配的屬性。結果是:

<p>test text</p> 

在視圖內呈現。

在我們thymeleaf模板,我們試圖做同樣的事情:

<p th:text="${referenceData}"/></p> 

但這只是簡單地返回一個空字符串。該視圖生成一個空字符串:

<p></p> 

(但我認爲EL實際上正在返回一個空)

我敢肯定,如果referenceData對象是一個範圍的屬性,如flowScopeflashScope這將工作 - 但它不是,它的屬性servletContext

有誰知道thymeleaf是否可以通過EL訪問servletContext?也許我需要使用不同的語法?

乾杯

彌敦道

回答

3

你可以通過#ctx對象,這是SpringWebContext類型的訪問常用的地圖。

例如對於Spring applicationContext,#ctx.locale,#ctx.httpServletRequest.contextPath,#ctx.servletContext甚至#ctx.applicationContext。

您可以用直接的方法調用

<p th:text="${#ctx.servletContext.getAttribute('referenceData')}">Whatever</p> 

或applicationAttributes變量使用Spring隱含對象

<p th:text="${application.referenceData}">Whatever</p> 
+0

謝謝Zemi地圖

<p th:text="${#ctx.servletContext.applicationAttributes.referenceData}">Whatever</p> 

或者更簡單的方法,這完美的作品。再次感謝 –

+0

我試圖做'$ {#ctx.getContextPath()}'但是這給了我一個錯誤,就好像該方法不存在一樣。我可以在Thymeleaf中調用'$ {#ctx.getContextPath()}'嗎? – trusktr