Spring boot 1.2.5.RELEASE 使用velocity模板中文乱码问题

application.properties文件:

spring.velocity.resourceLoaderPath=classpath:/templates/
spring.velocity.prefix=
spring.velocity.suffix=.vm
spring.velocity.cache=false
spring.velocity.check-template-location=true
spring.velocity.charset=UTF-8
spring.velocity.content-type=text/html

在使用spring boot开发中,虽然设置了编码,但是spring boot的这个版本还是会产生中文乱码,但是使用freemarker模板就没有问题,解决方法就是写一个VelocityAutoConfiguration.java文件放在工程中,覆盖掉spring boot 中的VelocityAutoConfiguration类,包名:

package org.springframework.boot.autoconfigure.velocity;

文件内容从spring boot源码中拷贝出来放在自己的工程,包名和文件名一样,修改的内容只需要在applyProperties添加一行代码:

velocityProperties.setProperty("input.encoding", this.properties.getCharset());

修改后的applyProperties方法如下:

protected void applyProperties(VelocityEngineFactory factory) {
	factory.setResourceLoaderPath(this.properties.getResourceLoaderPath());
	factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
	Properties velocityProperties = new Properties();
	velocityProperties.putAll(this.properties.getProperties());
	velocityProperties.setProperty("input.encoding", this.properties.getCharset());
	factory.setVelocityProperties(velocityProperties);
}

文件完整内容,保存到工程中就可以:

/*
 * Copyright 2012-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.autoconfigure.velocity;

import java.io.IOException;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.servlet.Servlet;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.template.TemplateLocation;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.view.velocity.EmbeddedVelocityViewResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.velocity.VelocityEngineFactory;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.velocity.VelocityConfig;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityViewResolver;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for Velocity.
 *
 * @author Andy Wilkinson
 * @since 1.1.0
 */
@Configuration
@ConditionalOnClass({ VelocityEngine.class, VelocityEngineFactory.class })
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(VelocityProperties.class)
public class VelocityAutoConfiguration {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private VelocityProperties properties;

    @PostConstruct
    public void checkTemplateLocationExists() {
        if (this.properties.isCheckTemplateLocation()) {
            TemplateLocation location = new TemplateLocation(
                    this.properties.getResourceLoaderPath());
            Assert.state(location.exists(this.applicationContext),
                    "Cannot find template location: " + location
                            + " (please add some templates, check your Velocity "
                            + "configuration, or set spring.velocity."
                            + "checkTemplateLocation=false)");
        }
    }

    protected static class VelocityConfiguration {

        @Autowired
        protected VelocityProperties properties;

        protected void applyProperties(VelocityEngineFactory factory) {
            factory.setResourceLoaderPath(this.properties.getResourceLoaderPath());
            factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
            Properties velocityProperties = new Properties();
            velocityProperties.putAll(this.properties.getProperties());
            velocityProperties.setProperty("input.encoding", this.properties.getCharset());
            factory.setVelocityProperties(velocityProperties);
        }

    }

    @Configuration
    @ConditionalOnNotWebApplication
    public static class VelocityNonWebConfiguration extends VelocityConfiguration {

        @Bean
        @ConditionalOnMissingBean
        public VelocityEngineFactoryBean velocityConfiguration() {
            VelocityEngineFactoryBean velocityEngineFactoryBean = new VelocityEngineFactoryBean();
            applyProperties(velocityEngineFactoryBean);
            return velocityEngineFactoryBean;
        }

    }

    @Configuration
    @ConditionalOnClass(Servlet.class)
    @ConditionalOnWebApplication
    public static class VelocityWebConfiguration extends VelocityConfiguration {

        @Bean
        @ConditionalOnMissingBean(VelocityConfig.class)
        public VelocityConfigurer velocityConfigurer() {
            VelocityConfigurer configurer = new VelocityConfigurer();
            applyProperties(configurer);
            return configurer;
        }

        @Bean
        public VelocityEngine velocityEngine(VelocityConfigurer configurer)
                throws VelocityException, IOException {
            return configurer.getVelocityEngine();
        }

        @Bean
        @ConditionalOnMissingBean(name = "velocityViewResolver")
        @ConditionalOnProperty(name = "spring.velocity.enabled", matchIfMissing = true)
        public VelocityViewResolver velocityViewResolver() {
            EmbeddedVelocityViewResolver resolver = new EmbeddedVelocityViewResolver();
            this.properties.applyToViewResolver(resolver);
            return resolver;
        }

    }

}
时间: 2024-08-28 19:47:28

Spring boot 1.2.5.RELEASE 使用velocity模板中文乱码问题的相关文章

001-Spring Cloud Edgware.SR3 升级最新 Finchley.SR1,spring boot 1.5.9.RELEASE 升级2.0.4.RELEASE注意问题点

一.前提 升级前 => 升级后 Spring Boot 1.5.x => Spring Boot 2.0.4.RELEASE Spring Cloud Edgware SR3 => Spring Cloud Finchley.SR1 1.1.Eureka Server ureka Server 依赖更新 升级前: <dependency> <groupId>org.springframework.cloud</groupId> <artifact

Spring Boot 2.2.2.RELEASE 版本中文参考文档

写在前面 在我初次接触MongoDB的时候,是为了做一个监控系统和日志分析系统.当时在用Java操作MongoDB数据里的数据的时候,都是在网上查找Demo示例然后完成的功能,相信大家也同样的体会,网上大都是这种一个入门的小Demo,很少有深入讲解的.功能调通后,自己琢磨效率方面的问题,便开始自己的瞎尝试之路,然后在产品启动阶段初始化多个MongoClient对象,搞了一个类似于连接池一类的池子,完成之后打心眼里觉得自己真是个小机灵鬼. 大概过了一年,为了系统地学习MongoDB的一些高级特性,

Spring Boot 2.2.2.RELEASE 版本中文参考文档【3.2 - 3.10】

Spring Boot 2.2.2.RELEASE版本中文文档持续更新中~如有需要获取参考文档文件,关注公众号JavaSo,回复“参考文档”即可. 3.2 结构化代码 Spring Boot不需要任何特定的代码布局即可工作.但是,有一些最佳做法会有所帮助. 3.2.1 使用“default”包 当一个类不包含引入包声明时,将其视为在默认包中.通常不建议使用默认包,应避免这种情况.对于使用@ ComponentScan,@ ConfigurationPropertiesScan,@ EntityS

Spring Boot 1.4.0 Release Notes 更新日志-02

Spring Framework 4.3 Spring Boot 1.4 builds on and requires Spring Framework 4.3. There are a number of nice refinements in Spring Framework 4.3 including new Spring MVC @RequestMapping annotations. Refer to the Spring Framework reference documentati

spring cloud: 升级到spring boot 2.x/Finchley.RELEASE遇到的坑

spring boot2.x已经出来好一阵了,而且spring cloud 的最新Release版本Finchley.RELEASE,默认集成的就是spring boot 2.x,这几天将一个旧项目尝试着从低版本升级到 2.x,踩坑无数,记录一下: 一.gradle的问题 spring boot 2.x 要求gradle版本不能太旧,先把gradle升级到4.6版本,然后编译,各种问题,到gradle官网上查了下,build.gradle有几个小地方要调整 1.1 java-libary 的项目

Spring Boot自动配置源码解析(基于Spring Boot 2.0.2.RELEASE)

在Spring Boot官方介绍中,首一段话是这样的(如下图).我们可以大概了解到其所表达的含义:我们可以利用Spring Boot写很少的配置来创建一个非常方便的基于Spring整合第三方类库的单体企业级应用.相信使用过Spring Boot的人都知道,她在这方面从前到后的一系列整合.本篇文字将带你进入具体的实现细节. 首先我们写一段Spring Boot应用启动类的代码如下: 1 package com.springTest; 2 3 import org.springframework.b

spring使用@Value注解读取.properties文件时出现中文乱码问题的解决

解决办法 在spring中我们常常使用.properties对一些属性进行一个提前配置, spring 在读取*.properties文件时, 默认使用的是asci码, 这时 我们需要对其编码进行转换. 下面列举两种常见的方法. 方法一:在配置spring.xml文件时,声明所需的∗.properties文件时直接使用"utf−8"编码 <context:property-placeholder location="classpath:conf/*.properties

spring boot 解决后台返回 json 到前台中文乱码之后出现返回json数据报错 500:no convertter for return value of type

问题描述 spring Boot 中文返回给浏览器乱码 解析成问号?? fastJson jackJson spring boot 新增配置解决后台返回 json 到前台中文乱码之后,出现返回json数据报错:no convertter for return value of type 注释掉解决中文乱码的问题之后返回对象json正常 Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWr

Spring boot 提高篇

Spring boot 提高篇 上篇文章介绍了Spring boot初级教程:构建微服务:Spring boot 入门篇,方便大家快速入门.了解实践Spring boot特性:本篇文章接着上篇内容继续为大家介绍spring boot的其它特性(有些未必是spring boot体系桟的功能,但是是spring特别推荐的一些开源技术本文也会介绍),对了这里只是一个大概的介绍,特别详细的使用我们会在其它的文章中来展开说明. github博文地址,阅读更佳 web开发 spring boot web开发