我正在尝试让我的 XSL 脚本使用 UTF-8 编码。像 åäö 和希腊字符这样的字符就像垃圾一样出现。让它工作的唯一方法是将结果写入文件。如果我将它写入输出流,它只会返回垃圾(System.out 有效,但这可能是因为它被重定向到文件)。
结果需要从 servlet 返回,请注意这不是 servlet 配置问题。我可以从 servlet 返回带有希腊字符的硬编码字符串,并且它工作正常,因此这是转换的问题。
这是我当前的(简化的)代码。
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
final TransformerFactory factory = this.getFactory();
final File inFile = new File("infile.xml");
final File xslFile = new File("template.xsl");
final File outFile = new File("outfile.html");
final Templates templates = factory.newTemplates(new StreamSource(xslFile));
final Transformer transformer = templates.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
final InputStream in = new FileInputStream(inFile);
final StreamSource source = new StreamSource(in);
final StreamResult result1 = new StreamResult(outFile);
final StreamResult result2 = new StreamResult(System.out);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final StreamResult result3 = new StreamResult(out);
//transformer.transform(source, result1);
//transformer.transform(source, result2);
transformer.transform(source, result3);
final Writer writer = response.getWriter();
writer.write(new String(out.toByteArray()));
writer.close();
in.close();
} catch (final TransformerConfigurationException e) {
e.printStackTrace();
} catch (final TransformerException e) {
e.printStackTrace();
}
}
另外,我的 XSL 脚本包含以下内容
<xsl:output method="html" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
让它发挥作用的正确方法是什么?我正在使用 Saxon 进行转换,如果这可能有任何帮助的话。
这几乎肯定是问题所在:
writer.write(new String(out.toByteArray()));
您已将文本仔细编码为 UTF-8,然后将其转换为字符串使用平台默认编码。你应该差不多never使用String
使用平台默认编码的构造函数和方法。即使你want要使用该编码,请明确执行。
如果你要写信给Writer
无论如何,你为什么要开始写信给一个ByteArrayOutputStream
?为什么不直接去Writer
?
然而,最好直接写入响应的输出流(response.getOutputStream()
),并设置响应的内容类型以指示它是 UTF-8。
请注意,如果您确实想获得结果String
事先,使用StringWriter
。写信给a是没有意义的ByteArrayOutputStream
然后转换为字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)