首先編寫過濾器代碼在src目錄下
package filter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyFilter implements Filter {
private FilterConfig fc;
public void init(FilterConfig fc) throws ServletException {
// TODO Auto-generated method stub
this.fc=fc;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding("gb2312");
response.setCharacterEncoding("gb2312");
chain.doFilter(request,response);
}
public void destroy() {
// TODO Auto-generated method stub
}
}
web.xml中的配置:
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.XX.XX.listener.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-patten>/*</url-patten>
</filter-mapping>