欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

拦截器demo

程序员文章站 2022-05-23 10:45:40
...

下面展示一些 内联代码片

自定义注解:

/**
 * @Author: 
 * @Date: 2020/4/30 10:10
 */
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyHandlerAnnonation {
    boolean tokenNonNull() default true;
}

webConfig配置:

/ * @Date: 2020/5/8 14:53
 *
 * 启用拦截器
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addInterceptor(new interceptor.MyInterCeptor()).addPathPatterns("/**").excludePathPatterns("/login");
    }
}

interceptor:

package com.example.interceptor.interceptor;

import com.example.interceptor.annonation.MyHandlerAnnonation;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 
 * @Date: 2020/5/8 15:06
 */
public class interceptor {
    /**
     * @Author: 
     * @Date: 2020/4/30 10:04
     */
    @Component
    public static class MyInterCeptor implements HandlerInterceptor {
        private static final String TOKEN_HEADER = "token";

        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (handler instanceof HandlerMethod) {
                HandlerMethod h = (HandlerMethod) handler;
                if (h.getMethod().isAnnotationPresent(MyHandlerAnnonation.class) || h.getMethod().getDeclaringClass().isAnnotationPresent(MyHandlerAnnonation.class)) {

                    MyHandlerAnnonation annotation = h.getMethod().getAnnotation(MyHandlerAnnonation.class);
                    String token = request.getHeader(TOKEN_HEADER);

                    if (annotation.tokenNonNull() == false && StringUtils.isEmpty(token)) {
                        return true;
                    }
                    if(!token.equals("1223")||StringUtils.isEmpty(token)){
                        throw new Exception("无权限访问,请登录");
                    }
                }
            }
            return true;
        }
    }
}

controller层:

@RestController
@RequestMapping("/yy")
public class MyController {

    @GetMapping("/kkk")
    @MyHandlerAnnonation()
    public void testHandler() {
        System.out.println("ffffffffffff");
    }
}
相关标签: interceptor