如何在 Velocity 上配置 UTF-8?
使用 Java、Servlet、MySQL、Tomcat 和 Velocity,采取以下步骤:
- velocity.properties:
- input.encoding=UTF-8
- output.encoding=UTF-8
- server.xml
- URIEncoding = UTF-8
字符集
- meta http-equiv="Content-Type" content="text/html;CHARSET=UTF-8"
- Eclipse 属性、项目属性、文件和文件编辑器编码
- 设置所有适用于 UTF-8 的内容
- 设置所有适用于 UTF-8 JDBC 连接的 :
- db.url=jdbc:mysql://:/?useEncoding=true&characterEncoding=UTF-8
- java/servlet 代码:
- request.setCharacterEncoding(UTF-8)
以上所有方法均无效。直到完成以下代码:
private String getParameter(String key) {
String param = request.getParameter(key);
if (Util.isNotEmpty(param)) {
try {
return new String(param.getBytes("8859_1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return param;
}
return null;
}
上面的意思是 request.setCharacterEncoding
没有效果( getCharacterEncoding()
确实返回 UTF-8 );知道请求包装器包装在 ThreadLocal 对象中。
这是如何引起的以及如何解决?
Using Java, Servlets, MySQL, Tomcat and Velocity, the following steps were taken:
- velocity.properties :
- input.encoding=UTF-8
- output.encoding=UTF-8
- server.xml
- URIEncoding = UTF-8
<html><head>
Charset- meta http-equiv="Content-Type" content="text/html;CHARSET=UTF-8"
- eclipse properties, project properties, file & editor encoding
- set all that apply to UTF-8
- JDBC connection:
- db.url=jdbc:mysql://:/?useEncoding=true&characterEncoding=UTF-8
- java/servlet code:
- request.setCharacterEncoding( UTF-8 )
All of the above didn't work. Until the following code was done:
private String getParameter(String key) {
String param = request.getParameter(key);
if (Util.isNotEmpty(param)) {
try {
return new String(param.getBytes("8859_1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return param;
}
return null;
}
The above means that request.setCharacterEncoding
didn't have an effect ( getCharacterEncoding()
does return UTF-8 ); knowing that the request wrapper is wrapped in a ThreadLocal
object.
How is this caused and how can I solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了正确解释参数,tomcat 需要将 URL 解析为 UTF-8。在 server.xml 连接器属性中设置此项,例如:
To interpret parameters correctly, the URL needs to be parsed as UTF-8 by tomcat. Set this in the server.xml connector properties, e.g. with:
您将获得以浏览器认为正确的编码方式编码的参数。不过,问题可能是基于奇怪的浏览器配置或 xml 标头 如果这曾经是使用 iso 编码的 XHTML,则可能需要它。
You'll get the parameters encoded in the encoding the browser finds OK. Though, Problem might be based on a weird browser configuration or an xml header <?xml version="1.0" encoding="iso8895_1" ?> which might have been needed if this was once XHTML with iso encoding.