• springboot中定义拦截器


    首先回忆一下springmvc中拦截器的使用:

    1.定义一个类 implements HandlerInterceptor,实现HandlerInterceptor接口中的方法

      preHandler               1

      postHandler              2

      afterCompletion        3

    2.配置拦截器 springmvc.xml

    <mvc:Interceptors>
      <mvc:Interceptor>
        <path="/user/*">
        <exinclud path="/user/login">
      </mvc:Interceptor>
    </mvc:Interceptors>

    springboot 中不建议使用xml文件,在使用拦截器的时候springboot框架自动配置

    springboot中定义和使用拦截器如下:

    1.开发自定义拦截器类

    拦截器类 implements HandlerInterceptor

    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            System.out.println("=======1=======");
            return true;
        }
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
            System.out.println("========2========");
        }
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            System.out.println("==========3========");
        }
    }

    2.配置拦截器,springboot自动配置(@Configuration)

    @Configuration
    public class MyWebConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInterceptor())
                    .addPathPatterns("/user/test")       //拦截项目中的哪些请求
                    .excludePathPatterns("/user/save");  //对项目中的哪些请求不拦截
        }
    }
  • 相关阅读:
    《天才在左,疯子在右》
    MVC思想概述
    java文件读写
    HTTP协议简单笔记
    自学Python_Day01
    Linux基础介绍篇
    PHP学习 Day_01
    Linux中部分命令英语全拼
    Linux学习基础命令(三)
    Linux学习基础命令(二)
  • 原文地址:https://www.cnblogs.com/lkldeblog/p/10636472.html
Copyright © 2020-2023  润新知