java代码
package com.itlwc.util;
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 MyFilter implements Filter {
private String encoding = "";
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化了");
// 返回filter的名字
encoding = filterConfig.getFilterName();
System.out.println(encoding);
//得到参数的名字
encoding = filterConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain fiterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
fiterChain.doFilter(request, response);
}
public void destroy() {
System.out.println("过滤器销毁了");
}
}
web.xml
<filter>
<filter-name>china</filter-name>
<filter-class>com.itlwc.util.MyFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GB2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>china</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>