上篇文章中说了SpringBoot中是如何使用servlet的,本文将讲解在SpringBoot中对过滤器Filter的实现

编写MyFilter实现Filter接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.maxbill.core.webbox.filter;

import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
* @功能 自定义过滤器
* @作者 zuoshuai(MaxBill)
* @日期 2017/7/6
* @时间 15:18
* @备注 MyFilter
*/
public class MyFilter implements Filter {

Logger log = Logger.getLogger(MyFilter.class);

@Override
public void init(FilterConfig config) throws ServletException {
log.info(">>>>>>>>>过滤器初始化>>>>>>>>>");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.info(">>>>>>>>>执行过滤操作>>>>>>>>>");
chain.doFilter(request, response);
}

@Override
public void destroy() {
log.info(">>>>>>>>>过滤器销毁>>>>>>>>>");
}

}

增加注解

1.过滤器增加@WebFilter注解,使能够被扫描到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter {

Logger log = Logger.getLogger(MyFilter.class);

@Override
public void init(FilterConfig config) throws ServletException {
log.info(">>>>>>>>>过滤器初始化>>>>>>>>>");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {
log.info(">>>>>>>>>执行过滤操作>>>>>>>>>");
chain.doFilter(request, response);
}

@Override
public void destroy() {
log.info(">>>>>>>>>过滤器销毁>>>>>>>>>");
}

}

2.启动类增加@ServletComponentScan注解,扫描项目中的filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.maxbill;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan
@SpringBootApplication
public class MaxbillApplication {

public static void main(String\[\] args) {
SpringApplication.run(MaxbillApplication.class, args);
}

}

启动项目测试:
INFO com.maxbill.core.webbox.filter.MyFilter:23 - >>>>>>>>>过滤器初始化>>>>>>>>>
INFO com.maxbill.core.webbox.filter.MyFilter:29 - >>>>>>>>>执行过滤操作>>>>>>>>>