java velocity入门_velocity入门(二)

本文详细介绍了使用Apache Velocity在Java Servlet中实现动态计算并将结果渲染到'add.vm'模板的示例。通过VelocityServlet和配置文件,展示了如何将变量a和b相加,并将结果显示在http://localhost:8080/helloapp/add页面上。
摘要由CSDN通过智能技术生成

项目结构:

f5c2ba10880e9849127d9a9f2a85bd1c.png

add.vm 源码:

Velocity Example

Velocity Example

$a+$b=$c

AddServlet.java 源码:

package mypack;

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import org.apache.velocity.*;

import org.apache.velocity.context.*;

import org.apache.velocity.servlet.*;

import org.apache.velocity.app.*;

import org.apache.velocity.exception.*;

public class AddServlet extends VelocityServlet {

protected Properties loadConfiguration(ServletConfig config)

throws IOException, FileNotFoundException {

Properties p = new Properties();

String path = config.getServletContext().getRealPath("/");

if (path == null) {

System.out.println("VelocityAdd.loadConfiguration():"

+ "unable to get the current webapp root. Using '/'. ");

path = "/";

}

p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);

p.setProperty("runtime.log", path + "velocity.log");

System.out.println("path=" + path);

return p;

}

public Template handleRequest(HttpServletRequest request,

HttpServletResponse response, Context context) {

Template outty = null;

try {

int a = 11;

int b = 22;

int c = a + b;

context.put("a", new Integer(a));

context.put("b", new Integer(b));

context.put("c", new Integer(c));

outty = getTemplate("add.vm");

} catch (ParseErrorException ex1) {

System.out.println("VelocityAdd: parse error for template " + ex1);

} catch (ResourceNotFoundException ex2) {

System.out.println("VelocityAdd: template not found " + ex2);

} catch (Exception ex3) {

System.out.println("VelocityAdd: error " + ex3);

}

return outty;

}

} web.xml配置如下:

add

mypack.AddServlet

add

/add

properties

mypack.PropertiesServlet

properties

/properties

properties_1

mypack.PropertiesServlet_1

properties_1

/properties_1

loop

mypack.LoopServlet

loop

/loop

浏览器输入:http://localhost:8080/helloapp/add

显示结果为:

efe06fe5055be6c5e85bd2566e0d9c54.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值