过滤器VS拦截器

示例代码

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package bj.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

/**
* Created by BaiJiFeiLong@gmail.com at 2018/4/21 13:52
*/
@SpringBootApplication
@RestController
public class DemoApp implements Filter, WebMvcConfigurer, HandlerInterceptor {
public static void main(String[] args) {
SpringApplication.run(DemoApp.class, args);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println(">>> Filter");
chain.doFilter(request, response);
System.out.println("<<< Filter Over");
}

@Override
public void destroy() {
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this);
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println(">>> Intercept");
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("<<< Intercept over");
}

@GetMapping("/")
public Object index() {
System.out.println("==> Executing ...");
return System.getenv().entrySet().stream()
.filter(x -> x.getValue().length() < 15)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}

执行结果

1
2
3
4
5
>>> Filter
>>> Intercept
==> Executing ...
<<< Intercept over
<<< Filter Over

文章首发: https://baijifeilong.github.io