spring boot 2.X 编写拦截器

目的:研究spring boot 2.X拦截器的实现原理,并编写本身的拦截器java

拦截器须要内容:web

                    一、自定义注解spring

                    二、自定义拦截器mvc

                    三、拦截器配置注入ide

实现代码ui

                    ①  自定义注解.net

    @Target 注解做用域:类、方法等blog

    @Retention 用来修饰注解,是注解的注解,标志注解的生命周期继承

package com.example.myproject.annotion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IntercepterRequired {


}

               ②自定义拦截器生命周期

    说明:自定义注解,继承HandlerInterceptorAdapter ,重写preHandle方法(请求方法前),具体拦截器的执行流程不明白的,你们在查查资料。

package com.example.myproject.intercepter;

import com.example.myproject.annotion.IntercepterRequired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (! (handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        IntercepterRequired annotation = method.getAnnotation(IntercepterRequired.class);
        if (null != annotation) {
            System.out.println("我真的拦截到了。。。。。。。。。。。");
            return true;
        }
        return true;
    }
}

                ③  拦截器配置注入

    @Configuration  把配置文件注入容器中

    @EnableWebMvc,是mvc的拦截器生效,若是缺乏此配置,自定义拦截器不生效

package com.example.myproject.config;

import com.example.myproject.intercepter.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class IntercepterConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
}

 

用例:

相关文章
相关标签/搜索