【问题标题】:Thymeleaf / Spring. get property key from ModelMap百里香/春天。从 ModelMap 获取属性键
【发布时间】:2017-10-18 00:20:59
【问题描述】:

我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。

在我的属性文件中:

signup.form.error.email.already.exists=Email (already taken)

在我的控制器中:

protected static final String ERROR_MESSAGE_KEY = "errorMessageKey";

model.addAttribute(ERROR_MESSAGE_KEY, "signup.form.error.email.already.exists");

在模板中:

 <div th:if="${errorMessageKey != null}" class="alert alert-danger alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">x</span>
                    </button>
                    <p th:text="#{errorMessageKey}" />                     
                </div>

但这是我在模板中看到的,而不是 电子邮件(已使用)

??errorMessageKey_en_US??

【问题讨论】:

    标签: java spring spring-boot thymeleaf


    【解决方案1】:

    将属性放入模型并不是您在 Thymeleaf 中解析属性的方式。请参阅docs,他们解释了如何正确操作。

    【讨论】:

      【解决方案2】:

      这是因为 Thymeleaf 正在尝试获取语言环境消息。默认情况下,它正在尝试 en_US。

      你可以看看这个answer

      【讨论】:

        【解决方案3】:

        尝试使用

        <p th:text="#{signup.form.error.email.already.exists}" />
        

        当您编写此代码时:

        model.addAttribute(ERROR_MESSAGE_KEY, "signup.form.error.email.already.exists");
        

        Spring 没有解析来自 message.properties 文件的消息:您只是将字符串 "signup.form.error.email.already.exists" 放入模型中...

        注意表达式 #{errorMessageKey} 返回包含指定消息的源文件的名称。

        【讨论】:

          猜你喜欢
          • 2015-12-09
          • 1970-01-01
          • 2014-06-04
          • 1970-01-01
          • 2018-05-23
          • 2017-08-02
          • 2018-11-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多