自定义 httpHandlers

1、在<system.web>下配置

<httpHandlers>
   <add verb="GET,HEAD" path="*.vm" type="NVelocityHandler" validate="false" />
  </httpHandlers>

2、创建 NVelocityHandler类,代码如下:

 

代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Commons.Collections;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using NVelocity;

/**/
/// <summary>
///
/// </summary>
public class NVelocityHandler : IHttpHandler
{
IHttpHandler Members;

public bool IsReusable
{
get { return false; }
}

public void ProcessRequest(HttpContext context)
{
// context.Response.Write("测试数据");
VelocityEngine velocity = new VelocityEngine();

ExtendedProperties props
= new ExtendedProperties();

//定义模板路径
props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, context.Server.MapPath(""));

//初始化
velocity.Init(props);

List
<City> list = new List<City>();

list.Add(
new City(21, "sh"));
list.Add(
new City(22, "bj"));
list.Add(
new City(23, "tj"));


IContext c
= new VelocityContext();

//添加到上下文中
c.Put("cities", list);

//根据请求输出
velocity.MergeTemplate("Template/test.vm", "UTF-8", c, context.Response.Output);

}
}

/**/
/// <summary>
/// 城市
/// </summary>
public class City
{

public City(int id, string name)
{
this.id = id;
this.name = name;
}
private int id;

public int Id
{
get { return id; }
set { id = value; }
}
/**/
/// <summary>
/// 名称
/// </summary>
private string name;

public string Name
{
get { return name; }
set { name = value; }
}
}

 

3、test.vm在根目录下,其了内容如下:

1##循环输出
2#foreach($city in $cities)
3Id:$city.id<br />
4城市名称:$city.name<br />
5#end
6##索引获取数据
7$cities.get_item(2).name

4、项目中需要引用NVelocity.dll

5、运行项目输入http://主机名/项目名/test.vm 你会惊奇的发现显示的效果。

posted @ 2010-03-09 16:38  why520crazy  阅读(342)  评论(0编辑  收藏  举报