上一篇文章里快速上手使用groovy来写页面了,如果在页面里使用中文的话,可能会遇到中文问题。在1.6.3版本的groovy里,可以设置两个属性来解决:
groovy.source.encoding=UTF-8
file.encoding=UTF-8
groovy在解释脚本时,默认会使用一个叫做groovy.source.encoding的系统属性的值来作为源码的编码,如果这也没有设置的话,就会使用file.encoding这个系统属性,也就是操作系统的默认字符集了。然而TemplateServlet很傻,它只认file.encoding,所以要两个属性都设置上,才能解决问题。而file.encoding属性是在整个jvm下都有效的,可能会带来其他的问题。下个版本中groovy会修正这个问题。如果你等不及了,你可以像我这样,hack一下TemplateServlet,把getTemplate()方法的一段代码改为:
//
// Template not cached or the source file changed - compile new
// template!
//
if (template == null) {
if (verbose) {
log("Creating new template from file " + file + "...");
}
String fileEncoding = System.getProperty("groovy.source.encoding");
Reader reader = null;
try {
reader = fileEncoding == null ?
new FileReader(file) : new InputStreamReader(new FileInputStream(file), fileEncoding);
template = engine.createTemplate(reader);
} catch (Exception e) {
throw new ServletException("Creation of template failed: " + e,
e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {
// e.printStackTrace();
}
}
}
cache.put(key, new TemplateCacheEntry(file, template, verbose));
if (verbose) {
log("Created and added template to cache. [key=" + key + "]");
}
}
用了如上的代码后就只要设置groovy.source.encoding一个属性就可以了。