springboot中拦截器--笔记

HandlerInterceptorAdapter

 通过继承HandlerInterceptorAdapter类可以实现请求拦截功能,在该类有三种方法经常用到

  • preHandle:在请求方法触发前,多用于请求拦截验证
  • postHandle:在请求方法触发后执行
  • afterCompletion:在整个请求处理完毕后进行回调(视图渲染完毕或者调用方已经拿到响应)

具体实现

 在springboot项目中首先创建DemoInterceptor类并继承HandlerInterceptorAdapter类

代码如下:

@Component
public class DemoInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在调用方法前触发
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("方法调用前");

        return true;
    }

    /**
     * 在方法调用后触发
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("方法调用后");
    }

    /**
     * 在整个请求处理完毕后进行回调(视图渲染完毕或者调用方已经拿到响应)
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("整个请求已处理完毕");
    }
}

上面代码已实现三个重要方法

将自定义的拦截器类配置到springboot中

 创建一个实现WebMvcConfigurer接口的实现类并重载addInterceptors方法。

代码如下:

@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

    @Autowired
    DemoInterceptor demoInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor).addPathPatterns("/demo/**").excludePathPatterns("/demo/two");
    }
}

  • addInterceptor:就是我们自定义的拦截器
  • addPathPatterns:表示要拦截的路径
  • excludePathPatterns:排除不需要拦截的路径

创建两个接口用于测试

@RestController
public class DemoController {

    @GetMapping("/demo/one")
    public String test1(){
        System.out.println("该请求会先经过拦截器");
        return "响应请求";
    }

    @GetMapping("/demo/two")
    public String test2(){
        System.out.println("该请求不会经过拦截器");
        return "响应请求";
    }
}


在浏览器中访问测试

http://localhost:8080/demo/one

image.png

image.png

http://localhost:8080/demo/two

image.png

image.png

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×