您的位置:首页 > 移动开发 > 微信开发

微信公众号入门笔记(四)velocity生成xml中文转义问题

2016-02-16 00:03 615 查看
作者:zhutulang

我对原来的代码做了重构,主要是用velocity来生成返回报文,非常的方便。

在这其中遇到了一个问题,但只是一个配置问题,却因为没有注意浪费了大量时间。因此特地记录下。。。

我发现生成的xml返回报文中,中文“乱码”了。我期望返回的文本消息是:

you发给me的是文本消息:this is a test

可是,用velocity生成的返回报文中却成了:
you发给me的是文本消息:this is a test

当然,这不是乱码。那么这种&#开头的到底是什么鬼。这跟html实体字符类似,原来就是所谓的NCR(numeric character reference)。具体可以看这篇博客:http://www.cnblogs.com/shishm/archive/2011/11/24/2261996.html 

实际上,这就是中文被转义了。因为我在velocity配置中配置了(第二行配置请忽略):

eventhandler.referenceinsertion.class = org.apache.velocity.app.event.implement.EscapeXmlReference
eventhandler.escape.xml.match = /RespMsg.*/

我在这里并不希望返回的xml报文对中文转义,可我为什么这么配置呢?因为这段配置我是从其它项目拷贝过来的。。。好吧,去掉就好了。

另外,velocity生成xml响应报文代码如下:

/**
* <p>Title: getXmlFromResponseMsg</p>
* <p>Description:根据velocity模板生成xml </p>
* @param vmName 模板名称
* @param responseMsg 响应消息对象
* @return
* @author zhutulang
* @version 1.0
*/
public static String getXmlFromResponseMsg(String vmName, BaseMsg responseMsg) {
StringWriter stringWriter = null;
try {
stringWriter = new StringWriter();
Template localTemplate = ve.getTemplate(vmName, "UTF-8");
HashMap<String,Object> localHashMap = new HashMap<String, Object>();
localHashMap.put("RespMsg", responseMsg);
localTemplate.merge(new VelocityContext(localHashMap), stringWriter);
stringWriter.flush();
}catch (Exception localException){
log.error("从Velocity模板生成相应XML时发生错误。", localException);
}
return stringWriter.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: