zoukankan      html  css  js  c++  java
  • SpringBoot使用拦截器

    SpringBoot的拦截器只能拦截流经DispatcherServlet的请求,对于自定义的Servlet无法进行拦截。
    SpringMVC中的拦截器有两种:HandlerInterceptor和WebMvcInterceptor。这两个接口都定义了请求之前、请求之中、请求之后三个函数,以HandlerInterceptor为例进行说明:

    • public boolean preHandle(HttpServletRequest req, HttpServletResponse httpServletResponse, Object o)
    • public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
    • public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)

    HandlerInterceptor的函数返回值都是boolean,一旦返回false,就不再处理这个请求,所以它真正具有拦截功能。而WebMvcInterceptor作用只是进行初始化,它的三个函数都是void类型的。

    要想使用HandlerInterceptor需要如下几个步骤:

    实现HandlerInterceptor接口

    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest req, HttpServletResponse httpServletResponse, Object o) throws Exception { 
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    
        }
    }
    

    添加Configureation

    过去可以用xml配置,现在更倾向于用java代码配置

    @Configuration
    public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
            super.addInterceptors(registry);
        }
    }
    
  • 相关阅读:
    strutr2运行流程
    ConcurrentHashMap原理分析
    面试题集锦
    jvm如何知道那些对象需要回收
    java中volatile关键字的含义
    关于Java类加载双亲委派机制的思考(附一道面试题)
    new关键字和newInstance()方法的区别
    Java中创建对象的5种方式 &&new关键字和newInstance()方法的区别
    字符串中第一个只出现一次的字符
    二进制数中1的个数
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/6329587.html
Copyright © 2011-2022 走看看