`

Grails引发的中文乱码问题

阅读更多

由写Grails过滤不良信息的Service引发的中文乱码问题

在一个Grails项目里面,我想写一个过滤不良信息的Service,而将过滤的规则放置在xml文件之中。

以下xml文件放置不良信息,包含单词、词组和句法,支持正则表达式:

<filter>
<words>
<word>fuck</word>
<word>反人民</word>
<word>去死吧</word>
<word>kill</word>
<word>bitch</word>
</words>
<phrases>
<phrase>asshole</phrase>
<phrase>beatyou</phrase>
</phrases>
<grammars>
<grammar>杀死*你</grammar>
<grammar>kick.*ass</grammar>
<grammar>impud.nce</grammar>
</grammars>
</filter>

然后是一个完成过滤功能的Service:

classFilterService...{
def
privatestaticnode=newXmlParser().parse(newFile('./config/filter.xml'))
staticStringfilter(Stringsource)...{

defsubstitution
=node.substitution.text()
defsensitive
=[node.words.word*.text().join('|'),
node.phrases.phrase
*.text().join('|'),
node.grammars.grammar
*.text().join('|')].join('|')

if(!source||!sensitive)returnsource
returnsource.replaceAll(sensitive,substitution)

}

}

就这样的代码,结果在Grails运行时出现中文问题,并且不止是页面,在filter方法里面就已经无法正确显示中文,而Service中同样的代码在普通Groovy应用程序中就没有中文问题。

按照以前J2EE开发的经验,尝试使用如下方法:

StringresultString=newString(testString.getBytes("iso-8859-1"),"UTF-8")

依旧乱码……

再次尝试:增加定义的运行参数-Dfile.encoding=UTF-8
无效……

xml文件中加入

<?xmlversion="1.0"encoding="UTF-8"?>

仍然无效……

 


 

琢磨了半天,得出解决方案:

譬如打算将整个项目编码统一成UTF-8格式的,我使用Eclipse开发,我的Eclipse默认的的编码是GBK的,那么这个可以保持不变,在项目上单击右键,选择Properties中的Resource,将Text file encoding设置成UTF-8。

注意:这样的后果是项目groovy等文件中原本使用GBK的中文会变成乱码!因此请选择合适的编码。

之后删除运行参数-Dfile.encoding=UTF-8,为什么使用了自定义运行编码参数反而出乱码,我也不知道。

再做一则改动

//将原来的
defnode=newXmlParser().parse(newFile('./config/filter.xml'))
//改为
defnode=newXmlParser().parseText(newFile('./config/filter.xml').getText())

最后,页面上面老规矩,加上<meta http-equiv="Content-Type" content="text/html; charset=GBK" />就可以了。

如果你的编码是GBK的,一样处理。

 

文章系本人原创,转载请注明作者和出处

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics