NVelocity中文乱码的问题
最近用NVelocity做个Demo,发现如果在模板中输入中文字符,那NVelocity输出就会出现乱码,
经过小弟的艰苦发掘,真于找出了个解决办法,现拿出与大家共享
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NVelocity;
using NVelocity.Context;
using System.IO;
using NVelocity.App;
using NVelocity.Runtime;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringWriter writer = new StringWriter();
Velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
Velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("Template"));
Velocity.SetProperty(RuntimeConstants.INPUT_ENCODING, "GB2312");
Velocity.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "GB2312");
Velocity.Init();
Template template = Velocity.GetTemplate("test.vm");
IContext context = new VelocityContext();
template.Merge(context, writer);
Response.Write(writer.ToString());
}
}
大家注意下面这两段话:using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NVelocity;
using NVelocity.Context;
using System.IO;
using NVelocity.App;
using NVelocity.Runtime;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringWriter writer = new StringWriter();
Velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
Velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("Template"));
Velocity.SetProperty(RuntimeConstants.INPUT_ENCODING, "GB2312");
Velocity.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "GB2312");
Velocity.Init();
Template template = Velocity.GetTemplate("test.vm");
IContext context = new VelocityContext();
template.Merge(context, writer);
Response.Write(writer.ToString());
}
}
Velocity.SetProperty(RuntimeConstants.INPUT_ENCODING, "GB2312");
Velocity.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "GB2312");
它们就是关键,它们分别告诉NVelocity读入也输出模板时采用什么编码,呵呵..Velocity.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "GB2312");
经过测试,已O了