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);
        }
    }
    
  • 相关阅读:
    MySQL
    Python练习-基于socket的FTPServer
    python练习-Socket实现远程cmd命令
    python概念-Socket到底有多骚
    Python练习-天已经亮了计算器也终于完成了
    python模块-logging的智商上限
    python正则表达式-re模块的爱恨情仇
    Python练习-os模块练习-还算是那么回事儿
    Python练习-time模块
    Python练习-跨目录调用模块
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/6329587.html
Copyright © 2011-2022 走看看