一、序言
因为我们公司的项目之前使用的版本是1.5.3版本的,但是目前需要使用模板引擎,对于freemarker、velocity一级thymeleaf的选型,也看了网上对应的讨论,说是velocity效率相比较最高,决定使用velocity,真正实际操作之后,发现springboot1.5+没有整合velocity,这就尴尬了,springboot 并没有减少对freemarker和thymeleaf的集成,但是捣鼓这么长时间,不想浪费心血,所以决定继续往下走。
参照的博文:https://zhuanlan.zhihu.com/p/28251412
二、解决方案
1、降低springboot版本为1.4
我想这种方式,网上一找一大把:https://blog.csdn.net/sinat_31270499/article/details/82283880
2、在springboot版本不变的情况下
来一张项目结构图
(1)引入jar包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
</dependencies>
(2)创建velocity和spring的整合的配置文件
扫描二维码关注公众号,回复:
11282580 查看本文章
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="mvcVelocityEngine" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/templates/" /><!-- 模板存放的路径 -->
<property name="configLocation" value="classpath:velocity.properties"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="false" />
<property name="prefix" value="/templates/" /><!-- 视图文件的前缀,即存放的路径 -->
<property name="suffix" value=".html" /><!-- 视图文件的后缀名 -->
<!--<property name="toolboxConfigLocation" value="/WEB-INF/tools.xml" /><!–toolbox配置文件路径–>-->
<property name="dateToolAttribute" value="date" /><!--日期函数名称-->
<property name="numberToolAttribute" value="number" /><!--数字函数名称-->
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="exposeSpringMacroHelpers" value="true" /><!--是否使用spring对宏定义的支持-->
<property name="exposeRequestAttributes" value="true" /><!--是否开放request属性-->
<property name="requestContextAttribute" value="rc"/><!--request属性引用名称-->
<!--<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/>-->
</bean>
</beans>
(3)添加配置文件velocity.properties
input.encoding=utf-8
output.encoding=utf-8
(4)将spring-velocity.xml文件引入到项目中
(5)写个html测试一下
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
亲爱的${toUserName},你好!
${message}
祝:开心!
${fromUserName}55
</body>
</html>
(6)测试
浏览器输入url,因为在application.yml或者application.properties文件中,没有配置任何信息,访问端口号默认为8080: