Can Thymeleaf access the Spring servletContext?

☆樱花仙子☆ 提交于 2021-02-07 10:57:19

问题


I wonder if anyone can help. We are in the process of converting a Spring Webflow 2 application from using a jsp based view layer, to a Thymeleaf based view.

For this most part this is OK, but now I'm struggling to get Thymeleaf to access an object that we've put in the servletContext.

So, we have an object that is put in the servletContext as part of a bean (implementing ServletContextAware and InitializingBean)

For the sake of simplicity, lets say it is a string:

public class ReferenceDataBuilder implements ServletContextAware, InitializingBean {

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

In our jsp based views, we can access the referenceData object like this:

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

By the magic of Spring EL, it knows the various scopes it has access to (servletContext, flowScope, flashScope etc), and (I'm guessing?) searches each scope until it finds a matching property. The result is that:

<p>test text</p>

is rendered within the view.

In our thymeleaf template, we are trying to do the same thing:

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

But this simply returns an empty string. The view renders an empty string:

<p></p>

(but I think the EL is actually being returned as a null)

I'm pretty sure that if the referenceData object were a property of a scope such as flowScope or flashScope this would work - but its not, its a property of servletContext.

Does anyone know if thymeleaf can access the servletContext via EL? Perhaps theres a different syntax I need to use?

Cheers

Nathan


回答1:


You could access usual maps via the #ctx object, which is of type SpringWebContext.

For example #ctx.locale, #ctx.httpServletRequest.contextPath, #ctx.servletContext or even #ctx.applicationContext for Spring applicationContext.

You could use direct method invocation

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

or the applicationAttributes variables map

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

or event simpler using Spring implicit object

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


来源:https://stackoverflow.com/questions/13949107/can-thymeleaf-access-the-spring-servletcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!