zoukankan      html  css  js  c++  java
  • Interceptor(拦截器)

    1. Interceptor类
    package cn.wolfcode.interceptor;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class DemoInterceptor implements HandlerInterceptor {
        //前置拦截器
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //在访问控制器之前拦截
            System.out.println("在访问控制器之前拦截");
            return true;
        }
        //试图解析器
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            //试图解析完拦截
        }
        //后置拦截器
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            //访问完控制器之后拦截
            System.out.println("访问完控制器之后拦截");
    
        }
    }
    1. SpringBoot配置
    package cn.wolfcode;
    
    import cn.wolfcode.filterdemo.FilterDemo;
    import cn.wolfcode.interceptor.DemoInterceptor;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @SpringBootApplication
    public class AppStart implements WebMvcConfigurer {
        /**
         * 配置过滤器
         * @return
         */
        @Bean
        public FilterDemo filterDemo(){
            return new FilterDemo();
        }
    
        /**
         * 配置拦截器
         * 配置类实现 WebMvcConfigurer接口
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //注册TestInterceptor拦截器
            InterceptorRegistration registration = registry.addInterceptor(new DemoInterceptor());
            registration.addPathPatterns("/**");                      //所有路径都被拦截
            registration.excludePathPatterns(                         //添加不拦截路径
    
            );
        }
    
    
        public static void main(String[] args) {
            SpringApplication.run(AppStart.class,args);
        }
    }
  • 相关阅读:
    spring framework体系结构及模块jar依赖关系
    Spring的核心jar包
    Spring AOP的理解和使用
    Spring特点与工作原理
    接口和抽象类的区别
    Java重载和重写的区别
    Jdk1.8中的HashMap实现原理
    Java集合中List,Set以及Map等集合体系详解
    Spring面试题整理
    ActiveMQ入门操作示例
  • 原文地址:https://www.cnblogs.com/dai-tao/p/13120646.html
Copyright © 2011-2022 走看看