目录

过滤器Filter

Filter概念

Filter的入门程序

Filter的生命周期

Filter的url-pattern配置

注解配置Filter

Filter 处理中文乱码

案例: 物品安全检查

过滤器链 FilterChain的执行过程

多个过滤器的先后执行顺序


过滤器Filter

Filter概念

过滤器: 过筛⼦,符合条件的过去,不符合条件不能过去.

Filter的入门程序

需求:

  • 浏览器要访问HelloServlet
  • 途径过滤期MyFilter, 若MyFilter放⾏,可执⾏访问到HelloServlet; 若不放⾏,⽆法访问HelloServlet

执行图解:

实现步骤

1. 编写Servlet, 在web.xml配置Servlet访问路径

2. 编写Filter,定义类, 实现接⼝Filter, 实现接⼝中抽象⽅法, 在web.xml配置Filter的访问过滤路径

代码: HelloServlet

/**
* @description ⽤于Filter⼊⻔案例演示
*/
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //控制台打印
         System.out.println("HelloServlet 执⾏了");
         //浏览器响应
         response.getWriter().println("Hello Servlet");
     }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doGet(request, response);
     }
}

代码: MyFilter

/**
* @description ⽤于演示Filter⼊⻔案例
*/
public class MyFilter implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
         System.out.println("MyFilter 执⾏了");
         //执⾏过滤后放⾏, 进⾏后续的请求访问
         chain.doFilter(req, resp);
     }
    public void init(FilterConfig config) throws ServletException {
     }
}

代码: 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_3_1.xsd"
     version="3.1">
     <!--配置servlet-->
     <filter>
         <filter-name>my</filter-name>
         <filter-class>com.wensong.filter.MyFilter</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>my</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>

     <!--配置Servlet-->
     <servlet>
         <servlet-name>hello</servlet-name>
         <servlet-class>com.wensong.servlet.HelloServlet</servlet-class>
     </servlet>
     <servlet-mapping>
         <servlet-name>hello</servlet-name>
         <url-pattern>/hello</url-pattern>
     </servlet-mapping>
</web-app>

Filter的生命周期

  • 过滤器对象的创建,是Tomcat服务器启动
    • init(FilterConfig config)过滤器对象被创建的时候调⽤,FilterConfig 对象tomcat引擎创建
  • 过滤器执⾏过滤的⽅法,过滤被访问资源的时候,必须是被过滤器过滤器的资源
    • doFilter(request,response)
  • 过滤器对象销毁的⽅法,销毁之前调⽤,服务器关闭
    • destroy()

Filter的url-pattern配置

  • 完全匹配
<!--
 过滤资源,只有hello
 绝对匹配 <url-pattern>/hello</url-pattern>
 只能过滤指定的资源
-->
<url-pattern>/hello</url-pattern>
  • ⽬录匹配
<!--
 ⽬录匹配,过滤器中最常⻅
 /abc/* 过滤abc⽬录下的所有资源
 ⼀次过滤⼀⽚资源
 过滤后台资源 /admin/*
-->
<url-pattern>/admin/*</url-pattern>
  • 后缀名匹配
<!--
 后缀名匹配,⼀般不使⽤
 *.jsp 访问所有jsp⽂件
-->
<url-pattern>*.jsp</url-pattern>

注解配置Filter

@WebFilter(urlPatterns="/过滤资源")

@WebFilter("/*")
public class ChinaFilter implements Filter {
 //代码省略...
}

Filter 处理中文乱码

需求:

使⽤过滤器Filter, 处理所有请求的中⽂乱码

执⾏图解:

代码: ChinaServlet

/**
* @description 获取请求参数中的中⽂
*/
@WebServlet("/china")
public class ChinaServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String username = request.getParameter("username");
         System.out.println("ChinaServlet , 获取请求参数 username = " + username);
     }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doGet(request, response);
     }
}

代码: ChinaFilter

/**
* @description 过滤中⽂,设置编码utf-8
*/
@WebFilter("/*")
public class ChinaFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
         //在过滤器中,设置request对象的编码表
         req.setCharacterEncoding("utf-8");
         //设置response缓冲区的编码表,通知浏览器的解码
         resp.setContentType("text/html;charset=utf-8");
         System.out.println("ChinaFilter执⾏了, 过滤中⽂,设置编码utf-8");
         chain.doFilter(req, resp);
     }
     public void init(FilterConfig config) throws ServletException {
     }
     public void destroy() {
     }
}

案例: 物品安全检查

需求:

实现对违禁品 进⾏过滤

执⾏图解:

代码: index.jsp

<body>
     <form action="${pageContext.request.contextPath}/safe" method="get">
         <h2>去海边游泳,请选择要携带的物品</h2>
         <input type="checkbox" name="product" value="泳裤" />泳裤
         <input type="checkbox" name="product" value="⽐基尼"/>⽐基尼
         <input type="checkbox" name="product" value="摄像机"/>摄像机
         <input type="checkbox" name="product" value="单反相机"/>单反相机
         <input type="checkbox" name="product" value="防晒油"/>防晒油
         <input type="checkbox" name="product" value="⼿榴弹"/>⼿榴弹
         <input type="checkbox" name="product" value="冲锋枪"/>冲锋枪
         <br />
         <input type="submit" value="提交" />
     </form>
 </body>

代码: SafeServlet

/**
* @description 安检通过,给浏览器响应结果
*/
@WebServlet("/safe")
public class SafeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         response.getWriter().print("违禁品已没收,安检通过的物品清单:" + request.getAttribute("list"));
     }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doGet(request, response);
     }
}

代码: SafeFilter

/**
* @description 携带商品的安全检查
*/
@WebFilter("/safe")
public class SafeFilter implements Filter {
     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
         //获取请求参数
         String[] products = req.getParameterValues("product");
         //物品过滤
         System.out.println("未做安检:" + Arrays.toString(products));
         List<String> list =Stream.of(products).filter(item ->!item.equals("⼿榴弹")).filter(item -> !item.equals("冲锋枪")).collect(Collectors.toList());
         System.out.println("做了过滤:" + list);
         //过滤后的物品 添加到域中
         req.setAttribute("list",list);
         chain.doFilter(req, resp);
     }
     public void destroy() {
     }
     public void init(FilterConfig config) throws ServletException {
     }
}

过滤器链 FilterChain的执行过程

⽣活中的过滤器链: 从 脏⽔ --> -->UF超滤膜 --> PP棉 -->前置活性炭 --> RO膜 --> 纳⽶晶须活性炭 --> 出纯⽔

Filter中的过滤器链 FilterChain: 由Tomcat引擎创建对象 作⽤: 维护过滤器执⾏顺序

⼩结: Servlet中doGet⽅法参数 request, response对象, 由Tomcat引擎创建, 经过多个过滤器⼀层层传递

多个过滤器的先后执行顺序

web.xml配置

  • 和配置⽂件的编写顺序决定运⾏的顺序,准确的说法是,根据mapping的顺序决定 (由上到下执⾏)

注解开发

  1. 注解开发没有配置⽂件的
  2. 按照类名的⾃然顺序决定: A-B-C
  3. 如果存在配置⽂件,配置⽂件优先

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐