简体   繁体   English

如何在Thymeleaf模板中访问系统属性?

[英]How to access system properties in Thymeleaf template?

I need to access system properties in a Thymeleaf template. 我需要访问Thymeleaf模板中的系统属性。 It would be nice if this was possible so that I don't have to populate the spring mvc model explicitly with properties. 如果这是可能的,那将是很好的,这样我就不必使用属性显式填充spring mvc模型。 I'm trying to use SPEL for this purpose but it's not working. 我正在尝试将SPEL用于此目的,但它无法正常工作。

<h2 th:text="${ systemProperties['serverName'] }">Service name</h2>

<h2 th:text="*{ systemProperties['serverName'] }">Service name</h2>

Both of these give me: 这两个都给了我:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1012E:(pos 17): Cannot index into a null value

Even if I try to access a jdk property it gives the same error so I know it's not the fact that the property is missing. 即使我尝试访问jdk属性它也会出现相同的错误,所以我知道这不是属性丢失的事实。 What am I doing wrong or is there another way to do this? 我做错了什么或者有其他方法可以做到这一点?

我用

${@environment.getProperty('myPropertyName')}

The link @Sudarshan_SMD posted gave me an idea and I finally got this to work as below. 链接@Sudarshan_SMD发布给了我一个想法,我终于得到了这个工作如下。

Put the following bean in your spring context. 将以下bean放在spring上下文中。

<bean id="sysprops" class="java.lang.System" factory-method="getProperties" />

Then access the bean directly as follows in your thymeleaf template. 然后在百万美元模板中直接访问bean

${@sysprops['yourPropertyName']}

This works because @sysprops allows direct access to the bean and the bean, which is java.lang.System, extends java.util.Hashtable and therefore allows key based access as opposed to function invocation based access. 这是有效的,因为@sysprops允许直接访问bean和bean,即java.lang.System,它扩展了java.util.Hashtable,因此允许基于密钥的访问,而不是基于函数调用的访问。 Doing it this way also means that you only have to define this bean once and use it across all your templates which is very convenient. 这样做也意味着您只需要定义一次这个bean并在所有模板中使用它非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM