1. 程式人生 > >SpringBoot整合thymeleaf(自定義)模板中文亂碼的解決辦法

SpringBoot整合thymeleaf(自定義)模板中文亂碼的解決辦法

樓主今天在學習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程式碼:

啟動專案之後:出現中文亂碼

 解決辦法如下圖:(在最上面的配置檔案相應位置加上下圖紅色箭頭部分的程式碼)

 

重啟專案即可解決中文亂碼問題: