由写Grails过滤不良信息的Service引发的中文乱码问题
在一个Grails项目里面,我想写一个过滤不良信息的Service,而将过滤的规则放置在xml文件之中。
以下xml文件放置不良信息,包含单词、词组和句法,支持正则表达式:
<filter>
<words>
<word>fuck</word>
<word>反人民</word>
<word>去死吧</word>
<word>kill</word>
<word>bitch</word>
</words>
<phrases>
<phrase>ass hole</phrase>
<phrase>beat you</phrase>
</phrases>
<grammars>
<grammar>杀死*你</grammar>
<grammar>kick .*ass</grammar>
<grammar>impud.nce</grammar>
</grammars>
</filter>然后是一个完成过滤功能的Service:

class FilterService ...{
def private static node = new XmlParser().parse(new File('./config/filter.xml'))
static String filter(String source) ...{
def substitution = node.substitution.text()
def sensitive = [node.words.word*.text().join('|'),
node.phrases.phrase*.text().join('|'),
node.grammars.grammar*.text().join('|')].join('|')
if(!source || !sensitive)return source
return source.replaceAll(sensitive,substitution)
}
}就这样的代码,结果在Grails运行时出现中文问题,并且不止是页面,在filter方法里面就已经无法正确显示中文,而Service中同样的代码在普通Groovy应用程序中就没有中文问题。
按照以前J2EE开发的经验,尝试使用如下方法:
String resultString = new String(testString.getBytes("iso-8859-1"),"UTF-8")依旧乱码……
再次尝试:增加定义的运行参数-Dfile.encoding=UTF-8
无效……
xml文件中加入
<?xml version="1.0" encoding="UTF-8"?>仍然无效……
琢磨了半天,得出解决方案:
譬如打算将整个项目编码统一成UTF-8格式的,我使用Eclipse开发,我的Eclipse默认的的编码是GBK的,那么这个可以保持不变,在项目上单击右键,选择Properties中的Resource,将Text file encoding设置成UTF-8。

注意:这样的后果是项目groovy等文件中原本使用GBK的中文会变成乱码!因此请选择合适的编码。
之后删除运行参数-Dfile.encoding=UTF-8,为什么使用了自定义运行编码参数反而出乱码,我也不知道。
再做一则改动
//将原来的
def node = new XmlParser().parse(new File('./config/filter.xml'))
//改为
def node = new XmlParser().parseText(new File('./config/filter.xml').getText())
最后,页面上面老规矩,加上<meta http-equiv="Content-Type" content="text/html; charset=GBK" />就可以了。
如果你的编码是GBK的,一样处理。
本文介绍了一种在Grails项目中解决中文乱码的方法,包括调整项目编码为UTF-8,修改XML解析方式,最终实现正确显示中文并过滤不良信息。
242

被折叠的 条评论
为什么被折叠?



