背景
在springboot1.4.x版本之前對velocity的模板支持的是相當好的,不止出于什么原因springboot從1.5.x以后停止了對velocity的支持,甚至在2.x版本中移除了和velocity的相關代碼。目前手上有些項目使用的是velocity模板引擎,同時也使用了springboot,現在想升級到springboot2.x,同時還想繼續使用velocity,怎么辦?springboot不支持,就自己想辦法支持下吧。 思路:把springboot早期版本的velocity支持單獨抽出一個jar。
步驟1:
1
|
git clone https: //github.com/spring-projects/spring-framework.git |
切換到 4.3.2.release 版本;拷貝org.springframework.ui.velocity和org.springframework.web.servlet.view.velocity 模塊下velocity的相關代碼;
步驟2:
1
|
git clone https: //github.com/spring-projects/spring-boot.git |
切換到v1.4.0.release;拷貝:org.springframework.boot.autoconfigure.velocity模塊下 velocity的相關代碼;
由于spring5.x及springboot2.x移除了velocity相關的代碼及配置,還要把spring.vm文件拷貝過來,整體代碼架構如下圖:
直接編譯打包
接入使用:
在項目中直接添加如下依賴:
1
2
3
4
5
|
<dependency> <groupid>com.dianwoda.velocity</groupid> <artifactid>spring-boot-velocity-starter</artifactid> <version> 1.0 . 0 -snapshot</version> </dependency> |
并添加如下配置:
1
2
3
4
5
6
|
spring.velocity.charset=utf- 8 spring.velocity.properties.input.encoding=utf- 8 spring.velocity.properties.output.encoding=utf- 8 spring.velocity.resourceloaderpath=classpath:/templates/ spring.velocity.suffix=.vm spring.velocity.toolbox-config-location=/web-inf/toolbox.xml |
在spring.xml中添加視圖解析配置:
1
2
3
4
5
6
7
8
9
10
|
<!-- 設置視圖解析工具 --> <bean id= "velocityviewresolver" class = "org.springframework.web.servlet.view.velocity.velocitylayoutviewresolver" > <property name= "cache" value= "false" /> <property name= "layouturl" value= "layout/layout.vm" /> <property name= "prefix" value= "/templates/" /> <property name= "suffix" value= ".vm" /> <property name= "exposespringmacrohelpers" value= "true" /> <property name= "contenttype" value= "text/html;charset=utf-8" /> <property name= "viewclass" value= "org.springframework.web.servlet.view.velocity.velocitylayoutview" /> </bean> |
按照上述配置即可在springboot2.x項目中使用velocity模板,歡迎有需要的小伙伴試用,使用過程中有問題可以直接反饋給我、
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://tech.dianwoda.com/2018/12/01/jie-jue-springboot2-xban-ben-dui-velocitymo-ban-bu-zhi-chi-de-fang-an/