【笔记】Velocity模板 和 Spring的整合配置 解决页面乱码的最佳方案, 简单Demo了解Velocity

xiaoxiao2021-02-28  101

Velocity是什么?

Velocity是一种基于java的模板引擎技术,有点类似与JSP,它允许页面设计者引用Java中定义的方法。前端页面设计者和后端Java开发者能够同时使用MVC的模式开发网站,这样前端能够把精力放在页面的设计上,后端也可以把精力放在代码开发上。Velocity把Java代码从Web页面中分离, 使网站可维护性更强.

项目中如何引入, 从一个简单demo开始

maven添加如下依赖

<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-tools</artifactId> <version>2.0</version> </dependency>

配置spring的视图解析配置 – Velocity视图解析器, 最简单的配置

Spring的配置文件在哪? 在项目web.xml中的<servlet>配置中, 找到DispatcherServlet的配置, 看contextConfigLocation的属性的value.

<!-- 一.配置试图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <!-- 1.前缀, 后缀 , 后缀是决定你模板的后缀的, 可以是其他例如.vm, 如果你喜欢的话 -- > <property name="prefix" value=""/> <property name="suffix" value=".html"/> <!-- 2.为解决页面乱码问题, 必须配置 --> <property name="contentType" value="text/html;charset=utf-8"/> <!-- 3.toolbox配置文件路径, 非必须--> <property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"/> </bean> <!-- 二.配置velocity模板路径, 配置文件路径等 --> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <!-- 1.模板位置路径 --> <property name="resourceLoaderPath" value="/WEB-INF/velocity/templates"/> <!-- 2.配置文件路径 --> <property name="configLocation" value="classpath:velocity/velocity.properties"/> </bean>
关于toolboxConfigLocation

这个toolbox.xml 配置文件 就是配置java后台写的工具类, 拿到页面上直接用.类似于jsp技术中的include某个工具类的用法.

<?xml version="1.0" encoding="UTF-8" ?> <toolbox> <tool> <key>StringUtil</key> <class>com.xxx.util.StringUtil</class> <scope>application</scope> </tool> </toolbox>

配置velocity.properties 最简单的配置

其实最简单的配置就是把编码设置上. 此处不配置编码, 页面会乱码. 同时如果少了上面的contentType配置, 同样乱码

input.encoding =UTF-8 output.encoding = UTF-8

HelloVelocity的模板文件

在上述的配置文件中resourceLoaderPath的路径下建立模板文件

<!DOCTYPE html> <html> <title>Hello Velocity模板文件</title> <body> <h1>Hello $name !</h1> <h2>当前时间 : $date !</h2> </body> </html>

$name和 $date 是velocity的语法, 类似于el 的 ${name} ${date}, 所以下一步上后台给这两个key赋值

后台Controller代码

@Controller @RequestMapping("/velocity") public class VelocityController { @RequestMapping(value="/test") public String test(Model model) { String name = "安仔"; model.addAttribute("name", name); model.addAttribute("date", new Date()); return "velocity"; } }

最终页面呈现类似于jsp, 但效率高于jsp


参考资料

Velocity详细配置讲解 官方文档翻译

转载请注明原文地址: https://www.6miu.com/read-48117.html

最新回复(0)