我多年来一直在 Tomcat Web 平台中使用 Apache Velocity。
我使用的是非常旧的版本:velocity-1.6.4 和velocity-tools-1.4 我最近决定迁移整个平台并使用 velocity-engine 2.3 和 velocity-tools 3.1
由于我有大约 15 个 Web 应用程序,因此该过程有点长,但非常简单。不幸的是,我遇到了一些渲染问题,特别是:
这是我得到的东西:
重音、美元、标点符号:àèù、$、! ?,
欧元符号:?
来自外部 js : �à �à $##!?�
相同的模板,具有相同的tomcat配置,但使用非常旧版本的velocity可以完美显示。如果是纯 HTML,它也可以工作(Tomcat 配置文件 server.xml 中的连接器精确为 UTF-8)。
所有内容均采用 UTF-8 格式。 velocityservlet 是一个基本的“velocityservlet”,尽可能简单。 在 Velocity 的最新版本中,速度属性配置文件仅包含:
resource.loaders = webapp
resource.loader.webapp.class = org.apache.velocity.tools.view.WebappResourceLoader
resource.loader.webapp.path = /WEB-INF/templates/
我已通过 servlet 内的代码检查属性 getVelocityProperty(RuntimeConstants.INPUT_ENCODING, RuntimeConstants.ENCODING_DEFAULT) 是否为 UTF-8。
经过日日夜夜的解决这个问题,我感到非常绝望! 谢谢您的帮助。
我发现我的问题了! 我的“字符集过滤器”没有过滤“响应”,而只是过滤请求。 然而,我对VelocityViewServlet类的initRequest方法的代码感到困惑:
protected void initRequest(HttpServletRequest request, HttpServletResponse response) 抛出 IOException { 尝试 { request.setCharacterEncoding(getVelocityProperty(RuntimeConstants.INPUT_ENCODING, RuntimeConstants.ENCODING_DEFAULT));
}
catch (UnsupportedEncodingException uee)
{
error(request, response, uee);
throw uee;
}
}
我想知道为什么 Velocity 不对响应应用 setCharacterEncoding。并且仅根据要求。 直观地说,我会添加response.setCharacterEncoding行: response.setCharacterEncoding(getVelocityProperty(RuntimeConstants.INPUT_ENCODING, RuntimeConstants.ENCODING_DEFAULT));
在旧版本的 Velocity 中,我们有 2 个配置参数: 输入.encoding=UTF-8 输出.编码=UTF-8
现在,只有一个: resource.default_encoding=UTF-8 但它应该应用于请求和响应。 我是不是漏掉了一点?
我今天也遇到了同样的问题,最后我重写了 VeloServlet 类中受保护的 setContentType 方法,问题得到了解决。我没有找到任何其他解决方案。
public class MyVeloServlet extends VelocityViewServlet {
...
@Override
protected void setContentType(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html; charset=UTF-8");
}
}