utf8 字符集与 Thymeleaf

2022-09-04 07:19:50

当使用Spring和Thymeleaf时,我所有的西里尔字符都显示在页面上。?????

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

正如这里所建议的那样:https://stackoverflow.com/a/11866822/1479414 和这里:https://stackoverflow.com/a/12023816/1479414 没有帮助。

如何解决这个问题?


答案 1

答案可以在这里找到:

应显式设置 和 的属性:characterEncodingtemplateResolverThymeleafViewResolver

<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>

答案 2

为我工作。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/");
   }
}

推荐