• 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);
        }
    }
    
  • 相关阅读:
    WPF Style和Template
    WPF自定义命令
    Vue-cli proxyTable 解决开发环境的跨域问题
    mongoose 获取某个存在的collecion 里的数据
    express+mongodb+mongoose简单入门
    服务器环境配置nginx / php / php-fpm(一)
    vue 循环前十条数据
    nodejs express的基本用法
    nodejs querystring
    nodejs fs.readFile
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/6329587.html
Copyright © 2020-2023  润新知