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代碼:

啟動項目之后:出現中文亂碼

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

 

重啟項目即可解決中文亂碼問題:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM