樓主今天在學習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:
然后測試Controller:
下面是我的HTML代碼:
啟動項目之后:出現中文亂碼
解決辦法如下圖:(在最上面的配置文件相應位置加上下圖紅色箭頭部分的代碼)
重啟項目即可解決中文亂碼問題: