Tomcat的中文處理(一)使用filter来改变request的编码2003-11-14 9:48:58
本文我们使用Filter来修改request的编码! 在 tomcat 自带的例子中有这个文件。 webapps\examples\WEB-INF\classes\filters\SetCharacterEncodingFilter.class 或者用下面的重新编译; 1)首先编写filter类: package myFilter; import java.io.IOException; import javax.servlet.*; public class ChangeCharsetFilter implements Filter { protected String encoding = null;/////要制定的编码,在web.xml中配置 protected FilterConfig filterConfig = null; public void destroy() { this.encoding = null; this.filterConfig = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getCharacterEncoding() == null){ String encoding = getEncoding();////得到指定的编码名字 if (encoding != null) request.setCharacterEncoding(encoding);////设置request的编码 } chain.doFilter(request, response);///有机会执行下一个filter } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding");///得到在web.xml中配置的编码 } protected String getEncoding() { return (this.encoding);///得到指定的编码 } } 2。编辑web.xml文件 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> /// 3。 写一个a.jsp <%@ page contentType="text/html; charset=GB2312" %> <% String name=request.getParameter("name");///本来这里得到字符是iso-8859-1编码的,不能直接 在Console中输出的,但是现在改变了request的编码方式,此时的name的编码是GB2312,所以能正确在Console中显示的。 System.out.println(name); %> <%=name%> 完! 关于中文处理的问题就写这些了! |
|
|