filter 转换字符编码

来源:互联网 发布:淘宝店铺复制免费 编辑:程序博客网 时间:2024/05/29 02:40

--整理自JavaWeb入门开发教程

转换中文字符编码过滤器的代码如下

//--------文件名:SetCharacterEncodingFilter.java--------------------
package filters;
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;
import javax.servlet.UnavailableException;
public class SetCharacterEncodingFilter implements Filter {
protected FilterConfig filterConfig;
protected String encodingName;
protected boolean enable;
public SetCharacterEncodingFilter() {
this.encodingName = "gb2312";
this.enable = false;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
loadConfigParams();
}
private void loadConfigParams() {
this.encodingName = this.filterConfig.getInitParameter("encoding");
String strIgnoreFlag = this.filterConfig.getInitParameter("enable");
if (strIgnoreFlag.equalsIgnoreCase("true")) {
this.enable = true;
} else {
this.enable = false;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(this.enable) {
request.setCharacterEncoding(this.encodingName);
}
chain.doFilter(request, response);
}
public void destroy() {
}
}

在上面这个过滤器中,init()方法从配置文件中取出字符编码格式的参数,在 doFilter()方法中使用 request 对象对所有的请求统一编码格式。
这个字符编码设置过滤器的配置信息如下。

<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
<init-param>
<param-name>enable</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

在上面这个过滤器中,初始化的时候提供了两个参数,参数 encoding 指明了编码格式为 gb2312,参数 enable 指明是否使用这个过滤器处理字符编码,在这里设置为 true,即启动这个字符编码过滤器,需要注意的是,这里的 enable 参数并不是所有过滤器必需的,只是在这个字符处理的程序中自己设定的一个参数,没有通用的含义。<url-pattern>/*</url-pattern>指明了对所有的请求都使用字符编码过滤器进行转码处理。这样就避免了对每个请求都进行字符编码设置,从而大大减少了工作量。经过这个字符编码格式转换过滤器的处理,所有来自客户的请求数据都被转换成 gb2312 的格式,这样就可以解决中文编码格式不同带来的乱码问题

这里需要注意:在 Tomcat 中,对 URL 和 GET 方法提交的表单是按照 ISO-8859-1 的格式进行编码的, 过滤器对这种情况并不起作用, 这时候就需要修改Tomcat 的配置文件来解决。

0 0