1.创建过滤器的实现类EncodingFilter.java,用于处理页面的字符编码格式。
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 EncodingFilter implements Filter {
private String encoding; // 编码方式,配置在web.xml中
private Boolean enabled; // 是否启用Filter,配置在web.xml中
public void init(FilterConfig config) throws ServletException {
// 初始化时加载参数
encoding = config.getInitParameter("encoding");// 编码方式
enabled = Boolean.valueOf(config.getInitParameter("enabled"));// 是否启用该Filter
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (enabled && !encoding.equals("")) {// 如果启用了此Filter
request.setCharacterEncoding(encoding);// request的编码
response.setCharacterEncoding(encoding);// response的编码
}
chain.doFilter(request, response);// 继续执行下一个Filter或者servlet
}
public void destroy() {
encoding = null;// 销毁时清空资源
}
}
2.在web.xml中配置初始化编码格式。
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.util.EncodingFilter</filter-class><!-- 类的完全限定名,即包名加类名 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value><!-- 编码 -->
</init-param>
<init-param>
<param-name>enabled</param-name>
<param-value>true</param-value><!-- 是否启用该Filter -->
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern><!-- 使用通配符*,所有请求都被该Filter处理 -->
</filter-mapping>