新建一个java类,里面继承Filter方法:
package TestServlet;
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 EncodingFilterTest implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("encodingFilter doFilter-----");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("过滤器初始化");
}
}
然后在web.xml进行配置:
然后当网站发出请求时就会进行过滤,并运行里面自己写的方法: