1.什么是Velocity

一种J2EE的前端模版技术,和JSP,Freemarker差不多,都是用来展示网页内容的。和JSP不同的是velocity只能显示Action中的数据,不能处理数据。不能写java代码,但是可以使用Velocity标记。也就是说把显示代码和后端的JAVA代码分离开来,降低程序的耦合性

2.需要引入哪些Jar包

velocity-1.5.jar,velocity-1.6.2.jar,velocity-tools-2.0.jar,velocity-tools-generic-2.0.jar,velocity-tools-view-2.0.jar

3.编写模板.vm文件

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<!-- 页面对变量赋值 -->
#set( $current = "Velocity22")
<!-- 输出 -->
$current is great! <br/>
<!-- 输出后台context设置的参数 -->
$name <br/> <!--String循环-->
#foreach( $elem in $arrList)
$elem</br>
#end <!--对象循环-->
#foreach( $elem in $userList)
名字:$elem.name 性别:$elem.sex 地址:$elem.address</br>
#end
</body>
</html>

4.编写servelet文件

package com.babybus.sdteam.servelet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Properties; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException; import com.babybus.sdteam.vo.User; public class VelocityTemplateServelt extends HttpServlet { private static final long serialVersionUID = 1L; @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException { // 设置request 和 response 编码,放置乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8"); // 获取页面输出流
PrintWriter out = response.getWriter(); // 创建Properties文件,也可以直接在目录下创建
Properties properties=new Properties();
properties.setProperty("resource.loader", "class");
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8"); // 创建模板引擎
VelocityEngine velocityEngine = null;
try {
velocityEngine = new VelocityEngine(properties);
} catch (Exception e) {
e.printStackTrace();
} // 创建上下文, 用于存放变量
VelocityContext context=new VelocityContext();
context.put("name", "test"); // List(String)
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("test01");
arrList.add("test02");
arrList.add("test03");
context.put("arrList", arrList); // UserList(存放对象List)
ArrayList<User> userList = new ArrayList<User>();
userList.add(new User("蔡大三", "男", "南安一中五条巷子"));
userList.add(new User("马大哈", "男", "红灯区"));
userList.add(new User("林超", "女", "下三路"));
context.put("userList", userList); // 读取模板文件流
StringWriter sw = new StringWriter();
try {
velocityEngine.mergeTemplate("templates/example.vm", "utf-8", context, sw);
} catch (ResourceNotFoundException e) {
e.printStackTrace();
} catch (ParseErrorException e) {
e.printStackTrace();
} catch (MethodInvocationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} // 输出到页面
out.println(sw.toString());
}
}

5.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name> <!--MyVelocity-->
<servlet>
<servlet-name>ve</servlet-name>
<servlet-class>com.babybus.sdteam.servelet.VelocityTemplateServelt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ve</servlet-name>
<url-pattern>/ve</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

6.输入地址:http://localhost:8080/velocitydemo/ve启动项目

本站文章为宝宝巴士 SD.Team原创,转载务必在明显处注明:(作者官方网站:宝宝巴士)

转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4827097.html

[JavaWeb基础] 020.Velocity 模板引擎简单示例的更多相关文章

  1. 转 如何使用velocity模板引擎开发网站

    基于 Java 的网站开发,很多人都采用 JSP 作为前端网页制作的技术,尤其在是国内.这种技术通常有一些问题,我试想一下我们是怎样开发网站的,通常有几种方法: 1:功能确定后,由美工设计网页的UI( ...

  2. Velocity模板引擎介绍

    整理下Velocity使用方法,整理比较详细用例 1 Velocity基础语法 1.1 用户和开发人员参考文档 http://velocity.apache.org/engine/releases/v ...

  3. velocity模板引擎学习(4)-在standalone的java application中使用velocity及velocity-tools

    通常velocity是配合spring mvc之类的框架在web中使用,但velocity本身其实对运行环境没有过多的限制,在单独的java application中也可以独立使用,下面演示了利用ve ...

  4. Velocity模板引擎语法

    Velocity 模板引擎介绍 Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java ...

  5. Velocity模板引擎入门

    类似于PHP中的Smarty,Velocity是一个基于Java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java代 ...

  6. 【转载】Velocity模板引擎的介绍和基本的模板语言语法使用

    原文地址http://www.itzhai.com/the-introduction-of-the-velocity-template-engine-template-language-syntax- ...

  7. 使用 Velocity 模板引擎快速生成代码(zhuan)

    http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ ****************************************** ...

  8. velocity模板引擎学习(3)-异常处理

    按上回继续,前面写过一篇Spring MVC下的异常处理.及Spring MVC下的ajax异常处理,今天看下换成velocity模板引擎后,如何处理异常页面: 一.404错误.500错误 <e ...

  9. 使用Velocity 模板引擎快速生成代码

    Velocity 模板引擎介绍 在现今的软件开发过程中,软件开发人员将更多的精力投入在了重复的相似劳动中.特别是在如今特别流行的MVC架构模式中,软件各个层次的功能更加独立,同时代码的相似度也更加高. ...

随机推荐

  1. 对MobileNet网络结构的解读

    引言 近几年来,CNN在ImageNet竞赛的表现越来越好.为了追求分类准确度,模型越来越深,复杂度越来越高,如深度残差网络(ResNet)其层数已经多达152层.但是在真实场景中如移动或者嵌入式设备 ...

  2. python进程/线程/协程

    一 背景知识 顾名思义,进程即正在执行的一个过程.进程是对正在运行程序的一个抽象. 进程的概念起源于操作系统,是操作系统最核心的概念,也是操作系统提供的最古老也是最重要的抽象概念之一.操作系统的其他所 ...

  3. checked 完整版全选,单选,反选

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel= ...

  4. asyncio异步编程【含视频教程】

    不知道你是否发现,身边聊异步的人越来越多了,比如:FastAPI.Tornado.Sanic.Django 3.aiohttp等. 听说异步如何如何牛逼?性能如何吊炸天....但他到底是咋回事呢? 本 ...

  5. OSG程序设计之更新回调

    更新回调(Update Callback)涉及到一个类:osg::NodeCallback.这个类重载了函数调用操作符.当回调动作发生时,将会执行这一操作符的内容. 如果节点绑定了更新回调函数,那么在 ...

  6. HTTP GET | POST | DELETE请求

    依赖: <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp& ...

  7. 李婷华 201771010113 《面向对象程序设计(java)》第一周学习总结

    第一部分:课程准备部分 填写课程学习 平台注册账号, 平台名称 注册账号 博客园:www.cnblogs.com 薄荷蓝莓 程序设计评测:https://pintia.cn/ 1957877441@q ...

  8. centos7启动httpd服务失败:Job for httpd.service failed because the control process exited with error code.

    centos7启动httpd命令有两个可以用 service httpd start    systemctl start httpd.service 如果出现如下报错 Job for httpd.s ...

  9. input唤起键盘影响移动端底部fixed定位

    主要代码如下: public docmHeight = document.documentElement.clientHeight || document.body.clientHeight; // ...

  10. 深度学习中的序列模型演变及学习笔记(含RNN/LSTM/GRU/Seq2Seq/Attention机制)

    [说在前面]本人博客新手一枚,象牙塔的老白,职业场的小白.以下内容仅为个人见解,欢迎批评指正,不喜勿喷![认真看图][认真看图] [补充说明]深度学习中的序列模型已经广泛应用于自然语言处理(例如机器翻 ...