1. 程式人生 > >springboot學習(七):Filter \Listener \Interceptor的使用

springboot學習(七):Filter \Listener \Interceptor的使用

說明

之前學了在springboot專案中過濾器、監聽器、攔截器的使用,在這裡記錄總結下。

正文

對於過濾器和監聽器,在springboot中可以使用兩種配置方式:
第一種,採用Servlet3.0的註解進行配置 @WebFilter @WebListener,使用此方式要在啟動類上使用@ServletComponentScan註解
第二種,使用配置bean的方式,springboot提供了FilterRegistrationBean和ServletListenerRegistrationBean

Filter

實現Filter介面建立自定義過濾器
第一種

@WebFilter(urlPatterns = "/hello",filterName = "demofilter")
public class DemoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

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

        System.out.println("Remote Host: " + servletRequest.getRemoteHost());
        System.out.println("Remote Address: " + servletRequest.getLocalAddr());
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

啟動類新增@ServletComponentScan

@SpringBootApplication
@ServletComponentScan
public class FilterApplication {

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

第二種
不需要在DemoFilter類上添加註解,在啟動類中建立bean

@SpringBootApplication
public class FilterApplication {

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

	@Bean
	public FilterRegistrationBean registrationBean(){
		FilterRegistrationBean filterbean = new FilterRegistrationBean();
		filterbean.setFilter(new DemoFilter());
		filterbean.setName("demofilter");
		filterbean.addUrlPatterns("/hello");
		return filterbean;
	}
}

Listener

實現ServletContextListener介面,建立專案啟動監聽類
第一種

@WebListener
public class DemoListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("DemoListener Context Initialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("DemoListener Context Destroyed");
    }
}

注意@ServletComponentScan一定不能忘

@SpringBootApplication
@ServletComponentScan
public class ListenerApplication {

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

第二種

@SpringBootApplication
public class ListenerApplication {

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

	@Bean
	public ServletListenerRegistrationBean<ServletContextListener> listenerRegistrationBean(){
		ServletListenerRegistrationBean listenerRegistrationBean= new ServletListenerRegistrationBean();
		listenerRegistrationBean.setListener(new DemoListener());
		return listenerRegistrationBean;
	}
}

Interceptor

對於攔截器,需要使用WebMvcConfigurerAdapter進行註冊,繼承此類重寫addInterceptors方法,將自定義的攔截器進行註冊。
實現HandlerInterceptor介面建立自定義攔截器

@Component
public class DemoInterceptor implements HandlerInterceptor {

    // This is used to perform operations before sending the request to the controller.
    // This method should return true to return the response to the client
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("Pre Handle method is Calling");
        return true;
    }

    // This is used to perform operations before sending the response to the client
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("Post Handle method is Calling");
    }

    // This is used to perform operations after completing the request and response
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("Request and Response is completed");
    }
}
@Component
public class DemoInterceptorConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private DemoInterceptor demoInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor).addPathPatterns("/hello");
    }
}

原始碼地址:
https://github.com/Edenwds/springboot_study/tree/master/filter
https://github.com/Edenwds/springboot_study/tree/master/listener
https://github.com/Edenwds/springboot_study/tree/master/interceptor

參考資料:
https://www.tutorialspoint.com/spring_boot/index.htm
https://blog.csdn.net/liu455042806/article/details/79875999?utm_source=blogxgwz0
https://blog.csdn.net/king_is_everyone/article/details/53116744?utm_source=blogxgwz5