---
# System prepended metadata

title: Filter(過濾器)
tags: [Java Web-mvc]

---

# Filter(過濾器)
###### tags: `Java Web-mvc`

1)Filter也屬於Servlet規範
```java=
import javax.servlet.*;
```
2)Filter開發步驟：新建類實現Filter接口，然後實現其中三個方法：init、doFilter、destroy
```java=
@WebFilter("*.do")
public class Filter01 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("A");
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
        //響應時的攔截
        System.out.println("A2");
    }

    @Override
    public void destroy() {

    }
}
```
  配置Filter，可以用註解@WebFilter，也可以使用xml文件<filter><filter-mapping>
```xml=
    <filter>
        <filter-name>Demo01Filter</filter-name>
        <filter-class>com.atguigu.filters.Demo01Filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Demo01Filter</filter-name>
        <url-pattern>/demo01.do</url-pattern>
    </filter-mapping>
```
    
3)Filter在配置時，和servlet一樣，也可以配置通配符，例如：@WebFilter("*.do")表示攔截所有以.do結尾的請求
```java=
@WebFilter("*.do")
```
4)過濾器鏈
  1.執行的順序依序是：A B C demo03 C2 B2 A2
![](https://i.imgur.com/cL5WDFo.png)

![](https://i.imgur.com/OrhNxFP.png)
  2.如果採取的是註解的方式進行配置，那麼過濾器的攔截順序是按照全類名的先後排順序排序的
  3.如果採取的是xml的方式進行配置，那麼按照配置的先後順序進行排序

5)補充：過濾器應用在添加編碼
```java=
@WebFilter(urlPatterns = {"*.do"},initParams = {@WebInitParam(name = "encoding",value = "UTF-8")})    
public class CharacterEncodingFilter implements Filter {

    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String encodingStr = filterConfig.getInitParameter("encoding");
        //如果沒有初始編碼，就設置為UTF-8
        if(StringUtil.isNotEmpty(encodingStr)){
            encoding = encodingStr;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//請求通過時，將編碼設置為UTF-8過濾添加後，發送請求到服務器  
    ((HttpServletRequest)servletRequest).setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
```    