首页 > 编程语言 > 详细

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

时间:2019-06-17 11:11:28      阅读:236      评论:0      收藏:0      [点我收藏+]

楼主今天在学习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

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

原文:https://www.cnblogs.com/jpfss/p/11038561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!