Web程序的编码问题主要有三个方面:
- 程序文件的编码;
- 输出页面到客户端的编码;
- 用户响应到服务器端的编码。
以设置为UTF-8为例,可以用如下方法解决。
1. 对于程序文件的编码
直接在Eclipse或者其他IDE,editor中将文件编码设为UTF-8即可。
2.输出页面
对于JSP页面,加入以下代码
<%@ page contentType="text/html; charset=UTF-8"%>
如果在IE或者Firefox中还不能正常显示,还可以在Html标识下加入下面的头信息
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
3. 响应到服务器端
我使用的是Tomcat,没有可以直接设置接受响应编码的方法(真是太佩服了!),但可以通过写一个Filter实现编码转化。
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null)
request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
将SetCharacterEncodingFilter放到程序的编译目录下,再在web.xml中添加相应属性
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>hijeff.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Tomcat就会将用户通过HTTP响应的字符转化为UTF-8的编码了
posted on 2007-03-15 20:58
hijeff 阅读(303)
评论(0) 编辑 收藏 所属分类:
Tomcat