嗨客网搜索
JavaEE Filter

描述

实现一个 JavaEE Filter 过滤器的功能。

题目

分别使用 XML 方式和注解的方式配置一个过滤器,然后分别创建一个 Servlet 验证拦截器作用。

题目解决思路

  1. 以 XML 配置的方式创建 FilterDemo01。
  2. 以注解的方式创建 FilterDemo02。
  3. 分别创建两个 Servlet 验证过滤器作用。

代码具体实现

XML方式配置过滤器

Filter 代码:

public class FilterDemo01 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("嗨客网(www.haicoder.net)\n"); System.out.println("过滤器拦截"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() {} }

web.xml 文件配置:

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--使用配置的方式写过滤器--> <filter> <!--过滤器的名字--> <filter-name>filter01</filter-name> <!--过滤器的完全限定名--> <filter-class>net.haicoder.filter.FilterDemo01</filter-class> </filter> <filter-mapping> <!--必须与上面的过滤器名字相同--> <filter-name>filter01</filter-name> <!--过滤器地址--> <url-pattern>/demo01</url-pattern> </filter-mapping> </web-app>

Servlet 代码:

@WebServlet("/demo01") public class ServletDemo01 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Servlet程序运行"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }

浏览器访问 Servlet,如下图:

01_Java Filter.png

控制台输出,如下图:

02_Java Filter.png

注解方式配置过滤器

Filter 代码:

// 配置要过滤的地址 @WebFilter("/demo02") public class FilterDemo02 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("嗨客网(www.haicoder.net)\n"); System.out.println("过滤器拦截"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() {} }

Servlet 代码:

@WebServlet("/demo02") public class ServletDemo02 extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Servlet程序运行"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }

浏览器访问 Servlet,如下图:

03_Java Filter.png

控制台输出,如下图:

04_Java Filter.png

以上案例分别使用 XML 配置的方式和注解的方式配置 Filter(两种配置任选其一即可)。

嗨客网顶部