您的位置:首页 > 编程语言 > Java开发

springboot1.5x版不支持velocity的解决方案

2017-08-01 01:08 381 查看
             springboot 在1.4版本中 融合了velocity,freemarker和thymeleaf模板。这个版本,如果想使用这些模板,只需要引入相应的starter pom就可以了。如 我想要在我的项目中使用thymeleaf模板。基本的步骤如下:

1. 引入starter 到pom

<!-- thymeleaf模板jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


2、在application的属性properties文件上配置 thymeleaf 相关属性

##thymeleaf start
#spring.thymeleaf.mode=HTML5
#spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
##开发时关闭缓存,不然没法看到实时页面
#spring.thymeleaf.cache=false
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
##thymeleaf end


只要上述的两个步骤,就可以在视图层渲染页面了。其他的 velocity和freemarker大体类似,不做赘述。

但是,问题来了,一开始我也以为事情就这么简单。但是在我引入了 velocity 模板之后,idea提示我
找不到jar。what? 瞬间懵逼了。 没按套路出牌啊?大家看下面的错误提示。


错误提示 是 unknown jar! 什么 ? velocity unkonwn? 不会吧? velocity 没集成到springboot? 我不信! 后来我烦了 spring-boot-dependencies 的pom 找,答案是果然没有!!咩有!石化表情

上网一查,我才知道

由于springboot1.5和以上版本 已经完全抛弃了velocity视图模板,所以,如果我们的系统,一直以来都是用的 velocity,而又希望用更高版本(>=1.5)的springboot,这就左右为难了。

但是不用也不行啊!总不能为了一个velocity就修改springboot版本吧! 没办法,自己引吧!

1、引入jar 带版本号的

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>


2、使用xml文件 自定义 velocity解析器!


3、将xml 引入到项目中

@ServletComponentScan
@SpringBootApplication
@ImportResource({"classpath:application-b.xml"})
public class Application extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}


4、如果想使用velocity 的自定义toolboox,还需要做如下的配置

在main下构建webapp目录,webapp目录下创建WEB-INF文件夹,然后把toolbox配置文件放到里边。

把toolbox 的xml地址 放到之前的 application-b.xml里。

经过我多次测试,只有放在这里,这有这样做才能被 velacity的 manager读取。所以只能是这样!

5、目前到这里,你以为就完了么?

答案是No! 在vm的页面上 使用自定义函数,你会发现,不好用! 没效果! 什么玩意啊! 根本就不调用好嘛!

不要着急 不要着急 !

在你调用的时候 ,你会惊喜的发现 后来有这两行提示

14-11-15 01:30:18:INFO org.apache.velocity.tools.view.servlet.ServletToolboxManager - Using config file '/WEB-INF/classes/velocity-toolbox.xml'
14-11-15 01:30:18:WARN org.apache.velocity.tools.view.XMLToolboxManager - XMLToolboxManager has been deprecated. Please use org.apache.velocity.tools.ToolboxFactory instead.


所以 原因大概已经清楚了! 因为你的velocity- toolbox 版本是2.0版本,XMLToolboxManager has been deprecated !

我还能怎么办!我也很无奈啊!

但是,经过我一下午的寻找终于找到了解决办法,方法也很简单,只要一招 ,妙解!

看清楚我下面的toolbox.xml怎么写的了么! xml的 root 元素 用<toolbox>替换<tools>!

<?xml version="1.0" encoding="UTF-8"?>
<toolbox>
<data key="foo">this is foo</data>
<tool>
<key>urlSign</key>
<scope>request</scope>
<class>com.github.qinyinglian.common.UrlSignUtil</class>
</tool>
</toolbox>


就可以了!

备注 :如果希望了解更多的我的其他技术分享,请关注 本人微信号 brave_gua 

有更多精彩的内容在等着大家!另外 辛苦编辑这篇文章不容易,请大家多支持,有问题请评论 谢谢大家。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息