如何在Thymeleaf + Spring + Tomcat中启用UTF-8支持?

时间:2016-05-04 12:42:56

标签: java spring tomcat utf-8 thymeleaf

我的应用程序的Thymeleaf配置设置为:

@Bean
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setCacheable(false);
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setPrefix(HTML_VIEWS);
    templateResolver.setSuffix(".html");

    return templateResolver;
}

@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.addDialect(new SpringSecurityDialect());
    templateEngine.addDialect(new LayoutDialect(new GroupingStrategy()));
    templateEngine.setTemplateResolver(templateResolver());

    return templateEngine;
}

@Bean
public ViewResolver viewResolver() {

    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(templateEngine());
    viewResolver.setCharacterEncoding("UTF-8");
    viewResolver.setCache(false);
    viewResolver.setOrder(1);

    return viewResolver;
}

OS(CentOS 7)默认编码为UTF-8,所有生成的文件都是UTF-8 enconding。我似乎无法正确显示字符。我尝试了一些在这里找到的建议,但没有用。

我已根据此处的一些建议尝试在我的Spring Security配置中在CharacterEncodingFilter之前设置CsrfFilter。此外,该应用程序将持久保存数据 WITH 奇怪的字符。

我的securitu配置以:

开头
@Override
protected void configure(HttpSecurity http) throws Exception {

    CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
    encodingFilter.setEncoding("UTF-8");
    encodingFilter.setForceEncoding(true);

    http.addFilterBefore(encodingFilter,CsrfFilter.class);
    // more security configs
}

我错过了什么?

1 个答案:

答案 0 :(得分:1)

该死的messages_pt_BR.properties文件与应用程序的其余部分有不同的编码...它决定使用ISO-8859-1。打败我为什么!