欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot(五) 整合interceptor

程序员文章站 2022-04-19 21:33:09
...

过滤器是java实现的,它需要依赖于Servlet容器,而拦截器是SprignMVC实现的一个机制,独立于Servlet容器,而且能实现IOC容器中的各个bean。简单的说:过滤器的urlPattern针对的是所有的请求,而拦截器的urlPattern针对的SpringMVC中的Controller控制器处理的请求,并不会拦截Servlet容器

 

一、创建一个自定义拦截器,继承HandlerInterceptor

 

@Component

public class MyInterceptor implements HandlerInterceptor {

    @Override

    public booleanpreHandle(HttpServletRequest request, HttpServletResponse response, Objecthandler) {

       System.out.println("preHandle"+request.getRequestURL().toString());

        return true; //返回false结束当前请求,返回true继续向下执行

   }

 

    @Override

    public voidpostHandle(HttpServletRequest request, HttpServletResponse response, Objecthandler, ModelAndView modelAndView) {

       System.out.println("postHandle");

 

    }

 

    @Override

    public voidafterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex) {

       System.out.println("afterCompletion");

    }

}


 

 

二、创建一个配置类,继承WebMvcConfigurer,重写addInterceptors 添加配置拦截器和拦截url

@Configuration

public class MyWebMvnAdapter implements WebMvcConfigurer {//WebMvcConfigurerAdapter已经过时

 

    @Autowired

    private MyInterceptormyInterceptor;

 

    @Override

    public voidaddInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(myInterceptor).addPathPatterns("/hello").addPathPatterns("/**");

    }

}

 


 

三、写一个controller

@RestController

@RequestMapping("hello")

public class HelloController {

 

    @RequestMapping(value ="world1",method = RequestMethod.GET)

    public String helloWorld1(){

        return"world1";

    }

 

    @RequestMapping(value ="world2",method = RequestMethod.POST)

    public String helloWorld2(){

        return"world2";

    }

}


 

 

 

 


相关标签: interceptor spring