文章目录
SpringBoot 拦截器与过滤器
1 区别

2 SpringBoot执行生命周期

3 Filter过滤器整合方式
两种方式:
1、使用spring boot提供的FilterRegistrationBean注册Filter
2、使用原生servlet注解定义Filter
两种方式的本质都是一样的,都是去FilterRegistrationBean注册自定义Filter
1 注解方式
通过注解的方式自动注入到Spring容器中
// 注入spring容器
@Component
// 定义filterName 和过滤的url
@WebFilter(filterName = "myFilter" ,urlPatterns = "/*")
public class My2Filter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// controller之前执行
logger.info("filter request;");
// 调用filter链中的下一个filter,过滤成功 执行chain.doFilter(request,response);
chain.doFilter(request,response);
// controller之后执行
logger.info("filter response;");
}
@Override
public void destroy() {
}
}
2 配置方式
2.1 创建过滤器类
不需要新增注解,以@Bean的方式注入到Spring容器中
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override`在这里插入代码片`
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// controller之前执行
logger.info("filter request;");
// 调用filter链中的下一个filter,过滤成功 执行chain.doFilter(request,response);
chain.doFilter(request,response);
// controller之后执行
logger.info("filter response;");
}
@Override
public void destroy() {
}
}
2.2 配置类Config
@Configuration
public class Config {
@Bean
public FilterRegistrationBean registrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
4 Interceptorr拦截器整合
4.1 创建拦截器类
/**
* 拦截器
*/
public class GateInterceptor implements HandlerInterceptor {
// controller执行之前调用
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
// 在controller return之前调用
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
// 在controller return 之后调用
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
4.2 配置拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
// 可以添加多个拦截器,执行按先后顺序执行
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new Interceptor());
}
}
1535

被折叠的 条评论
为什么被折叠?



