Filter
Filter
Filter:过滤器:用来过滤网站的数据
Filter:开发步骤
-
导包
-
编写过滤器
-
导包不要错误
-
实现Filter接口,重写方法
@WebFilter("/*") public class CharacterEncodingFilter implements Filter { // 初始化 web服务器启动已经初始化了 public void init(FilterConfig filterConfig) throws ServletException { System.out.println("初始化文件"); } // chain:链 /* * * 1、过滤器中的所有代码,再过滤特定请求的时候会执行 * 2、必须要让过滤器继续执行下去*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); System.out.println("CharacterFilter执行前"); chain.doFilter(request,response); //让请求继续走下去,如果不写,,程序到这里就被拦截了 System.out.println("CharacterFilter执行后"); } // 销毁 :web服务器关闭的时候过滤器销毁 public void destroy() { System.out.println("文件被销毁了"); } }
-
在xml中配置Filter
<filter> <filter-name>CharterFilter</filter-name> <filter-class>com.yt.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharterFilter</filter-name> <!-- 只要是servlet下的任何请求,都会经过这个过滤器--> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
-
测试过滤器的servlet
public class ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setCharacterEncoding("utf-8");
resp.getWriter().write("你好呀!世界");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}