Вопрос

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

Это было полезно?

Решение

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>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top