楼主今天在学习SpringBoot集成thymelaf的时候报了中文乱码的错误,经过网上的搜索,现在得到解决的办法,分享给大家:

package com.imooc.config;

import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver; /**
* WebMvc的配置类(自定义Thymeleaf模板)
*
* @author Liao Huan
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { private ApplicationContext applicationContext; /**
* 设置上下文
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
} /**
* Thymeleaf模板资源解析器(自定义的需要做前缀绑定)
*/
@Bean
@ConfigurationProperties(prefix = "spring.thymeleaf")
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext);
return templateResolver;
} /**
* Thymeleaf标准方言解释器
*/
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
//支持spring EL表达式
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
} /**
* 视图解析器
*/
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine()); return thymeleafViewResolver;
}

我使用的是自定义的thymelefa模板,在配置文件中需要手动去配置上面的几个方法,这里给出thymeleaf部分配置文件和Controller类的截图代码:

applicaiton.properties:

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

然后测试Controller:

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

下面是我的HTML代码:

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

启动项目之后:出现中文乱码

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

解决办法如下图:(在最上面的配置文件相应位置加上下图红色箭头部分的代码)

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

重启项目即可解决中文乱码问题:

SpringBoot集成thymeleaf(自定义)模板中文乱码的解决办法-LMLPHP

原文地址:https://blog.csdn.net/qq_32575047/article/details/82927873

05-11 11:04