velocity初体验

VelocityServlet:

package org.liufei.velocity;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;

@SuppressWarnings("deprecation")
public class AddServletVelocity extends VelocityServlet {

private static final long serialVersionUID = -5343161778899944087L;

@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) throws Exception {
Template template = null ;
try{
int a = 11 ;
int b = 22 ;
int c = a + b ;
ctx.put("a", new Integer(a)) ;
ctx.put("b", new Integer(b)) ;
ctx.put("c", new Integer(c)) ;
template = getTemplate("add.vm") ;
}catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
return template;
}

@Override
protected Properties loadConfiguration(ServletConfig servletConfig) throws IOException, FileNotFoundException {
Properties properties = new Properties() ;
String path = servletConfig.getServletContext().getRealPath("/") ;
if(path == null){
System.out.println("Error !");
path = "/" ;
}
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path) ;
properties.setProperty("runtime.log", path + "velocity.log") ;
properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
return properties ;
}

}



vm模板:
<html>
<head>
<title>Velocity Test</title>
</head>
<body>
<h1>Velcity Excemple</h1>
<p>$a + $b = $c</p>
</body>
</html>


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">

<servlet>
<servlet-name>add</servlet-name>
<servlet-class>org.liufei.velocity.AddServletVelocity</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>

<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
</web-app>

运行结果:
Velcity Excemple

11 + 22 = 33
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值