Search code examples
javaspringutf-8intellij-ideathymeleaf

Messages from .properties file do not display UTF-8 characters


As the title says, I can only add that if I enter ą ę ó manually in html file, it's fine.

ViewResolver:

<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <property name="cacheable" value="false"/>
    <property name="characterEncoding" value="UTF-8"/>
</bean>

<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />
</bean>

<bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
    <property name="characterEncoding" value="UTF-8"/>
    <property name="order" value="1"/>
</bean>

pom.xml:

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

example of html input:

<h2><p th:text="#{homepage.greeting}">Welcome</p></h2>

inside the tag of the html file:

<meta charset="UTF-8"/>

In IntelliJ Idea I have set project encoding to UTF-8, default encoding for properties files to UTF-8 enter image description here

And I honestly have no idea where is the problem. When I change locale to pl, this is the output: enter image description here

Sorry but I can't post images yet. Any help would be greatly appreciated.

Tried this filter in web.xml, still no luck.

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Solution

  • Okay, I figured it out. Here's the deal:

    I had the following code:

    <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages" />
    </bean>
    

    Option 1: Just add this as another property:

    <property name="defaultEncoding" value="UTF-8"/>
    

    Option 2: Changed it to:

    <bean id="messageSource"
          class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
    

    If you change it to reloadable, keep in mind to also change the property value from "messages" to "classpath:messages". For some reason it couldn't find the message bundle if I didn't change it.