SpringBoot第一章过滤器

1、创建过滤器,注意:controller 、filter、config需要放置在application的子包下面,否则扫描不到,用于请求管道

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //servletResponse.getWriter().write("777");
        System.out.println("拦截器拦截成功");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}

  

2、注解方式注册过滤器

/**
 * Servlet Filter implementation class MyFilter
// */
//@WebFilter(
//        dispatcherTypes = {
//                DispatcherType.REQUEST,
//                DispatcherType.FORWARD,
//                DispatcherType.INCLUDE,
//                DispatcherType.ERROR
//        },
//        asyncSupported = true,
//        description = "MyFilter器4",
//        urlPatterns = {"/gg"},
//        initParams = {
//                @WebInitParam(name = "name", value = "编程帮", description = "name的描述")
//        },
//        servletNames = {"SuccessServlet"})

3、配置类FilterConfig注册,自动扫描自动注册

@Configuration
public class FilterConfig {

@Bean
public FilterRegistrationBean heFilterRegistration() {

FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());

filterRegistrationBean.addUrlPatterns("/*");

return filterRegistrationBean;
}
}

posted on 2021-10-27 15:25  topguntopgun  阅读(58)  评论(0编辑  收藏  举报

导航