utf8 charset with Thymeleaf
Asked Answered
R

7

14

When using Spring with Thymeleaf all my Cyrillic characters are shown as ????? on pages.

Using

@RequestMapping(value = "/login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")

as it was suggested here: https://mcmap.net/q/165569/-who-sets-response-content-type-in-spring-mvc-responsebody and here: https://mcmap.net/q/300481/-utf-8-encoding-problem-in-spring-mvc doesn't help.

How to solve this issue?

Reo answered 4/4, 2016 at 7:52 Comment(0)
R
26

The answer can be found here:

Property characterEncoding should be explicitly set for templateResolver and ThymeleafViewResolver:

<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    ...
    <property name="characterEncoding" value="UTF-8"/>
    ...
</bean>

<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    ...
    <property name="characterEncoding" value="UTF-8"/>
    ...
</bean>
Reo answered 4/4, 2016 at 7:54 Comment(2)
I've changed both settings but the unicode characters still do not render properly. Is there any other setting that could be misconfigured?Surprisal
I don't know. I have not been working with Tapestry for two years. It might be that something has changed since that timeReo
G
5

working for me. java config

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.projectName.controller")
public class MVCConfig implements WebMvcConfigurer, ApplicationContextAware {

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
         BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver viewResolver(){
        ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
        thymeleafViewResolver.setTemplateEngine(templateEngine());
        thymeleafViewResolver.setCharacterEncoding("UTF-8");
       return thymeleafViewResolver;
    }

    @Bean
    public TemplateEngine templateEngine(){
       SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
       springTemplateEngine.setEnableSpringELCompiler(true);
       springTemplateEngine.setTemplateResolver(templateResolver());
       return springTemplateEngine;
   }

   @Bean
   public ITemplateResolver templateResolver(){
       SpringResourceTemplateResolver springResourceTemplateResolver = new 
                        SpringResourceTemplateResolver();
       springResourceTemplateResolver.setApplicationContext(applicationContext);
       springResourceTemplateResolver.setPrefix("/WEB-INF/views/");
       springResourceTemplateResolver.setTemplateMode(TemplateMode.HTML);
       springResourceTemplateResolver.setSuffix(".html");
       springResourceTemplateResolver.setCharacterEncoding("UTF-8");
       return springResourceTemplateResolver;
  }

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry
            .addResourceHandler("/resources/**")
            .addResourceLocations("/resources/");
   }
}
Gretna answered 25/7, 2018 at 6:38 Comment(2)
Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. ThanksBensky
Boiletplate advise. Thanks!Intellection
D
2

in Config

public class SpringConfig implements WebMvcConfigurer {

    private final ApplicationContext applicationContext;

    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        registry.viewResolver(resolver);
    }
}

In ServletInitializer

public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        return new Filter[] { filter };
    }
}
Decarbonate answered 8/1, 2021 at 21:49 Comment(2)
This is all good, until Filter[] getServletFilters(), that isn't in AbstractAnnotationConfigDispatcherServletInitializer, but in AbstractDispatcherServletInitializer. How did you override it? @DecarbonateEpiglottis
Link to documentation. AbstractAnnotationConfigDispatcherServletInitializer extends AbstractDispatcherServletInitializerDecarbonate
B
0

If you have added <property name="characterEncoding" value="UTF-8"/> in the bean configuration for view resolver and still text are not shown in correct format then the problem is in the properties/resource_bundle files.

Try encoding UTF-8 or non-English characters with native2ascii tool. (its included in the java_home/bin folder.

Bare answered 16/1, 2020 at 5:38 Comment(0)
F
0

In my case, I put below 2 lines in application.properties file

spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8

(Korean)Reference: https://blog.thjang.net/33

Formant answered 21/11, 2021 at 12:34 Comment(0)
S
0

With Spring WebFlux, I've restricted the view resolver to use text/html; charset=UTF-8 as the only supported content type. I've used a custom WebFluxConfigurer for that (in Kotlin):

class CustomWebFluxConfigurer(
    private val viewResolver: ThymeleafReactiveViewResolver
) : WebFluxConfigurer {
    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        viewResolver.supportedMediaTypes =
            listOf(MediaType.parseMediaType("text/html; charset=UTF-8"))
        registry.viewResolver(viewResolver)
    }
}
Selwin answered 9/2, 2022 at 13:17 Comment(0)
M
-2

I think in thymeleaf html page you are using th:text with html element, th:text it just display normal text,

if you want use special charter with your thymeleaf html page so just need to change for example

th:utext="${yourcontroller_var}"

or

th:utext="#{properties_var}"

For example

<div th:utext="${user.name}"> Test! </div> // for your controller variable 

And

<div th:utext="#{message.username}"> UserName! </div> // for your properties variable 

Nothing do other configuration for using special character with thymeleaf html page.

Hope you will fix your problem

Michaelmas answered 4/4, 2016 at 9:4 Comment(2)
You are wrong, this will not fix problem when page has static text and file is in utf-8 encoding.Reo
@Reo what would fix this?Karleenkarlen

© 2022 - 2024 — McMap. All rights reserved.