过滤器
# 说明
使用OncePerRequestFilter
过滤器,好处是入参直接为HttpServletRequest,无需转换。
# 样例
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;
@Configuration
public class FilterConfig {
/**
* 全局过滤器
*
* @return filter
*/
@Bean
public OncePerRequestFilter globalFilter() {
return new GlobalFilter();
}
/**
* 全局过滤器
* 优先级:1(最高,order的数值越小,则优先级越高)
*
* @return FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean<OncePerRequestFilter> globalFilterRegistrationBean() {
FilterRegistrationBean<OncePerRequestFilter> filterRegistrationBean = new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(globalFilter());
filterRegistrationBean.addUrlPatterns(GLOBAL_FILTER_PATTERNS);
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}
}
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
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
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 全局过滤器
*
*/
public class GlobalFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
编辑 (opens new window)
上次更新: 2024/05/15, 22:41:17