定义登录拦截器注解

  • 定义登录拦截器注解
/**
 * 定义登录拦截器注解
ElementType.METHOD:为运行在方式上
ElementType.TYPE:为运行在class、interface上
@Retention(RetentionPolicy.RUNTIME)为元注解,在编译时
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {

}

  • 拦截器
public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        LoginRequired loginRequired = this.findAnnotation((HandlerMethod) handler, LoginRequired.class);

        if (loginRequired == null) {
            return false;
        } else {
            System.out.println("开始验证");
            if ("pass".equals(request.getHeader("token"))) {
                return true; //放行
            } else {
                return false; //拦截
            }
        }
//        return true;  //false拦截,true为放行
    }
/**
handlerMethod->这里可理解为请求,请求中包含请求路径,
getBeanType() ->返回请求方法的类型,(一般为className)
getAnnotation()->返回该类型上的指定字节码的注解
*/
    private <T extends Annotation> T findAnnotation(HandlerMethod handlerMethod, Class<T> annotationType) {
        T annotation = handlerMethod.getBeanType().getAnnotation(annotationType);
        if (annotation != null) {
            return annotation;
        }
        return handlerMethod.getMethodAnnotation(annotationType);
    }
}


  • 配置文件

    <!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.itClass.SpringMVC.MyInterceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
  • 注解方式定义配置类


@Configuration
@ComponentScan //默认会扫描当前包下的注解,若不配置,spring容器将不能扫描到@Configuration注解
public  class InterceptConfig extends WebMvcConfigurerAdapter {

    @Bean
    public MyInterceptor myInterceptor() {
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
    }
}
  • 测试类

@Controller
@RequestMapping("/mvc")
@LoginRequired
public class helloWorld {

    @RequestMapping("hello")
    public String helloDemo(Model model) {
        model.addAttribute("name", "iCopper");

        return "hello";
    }

    @RequestMapping("hello02")
    public String helloDemo02(Model model) {
        model.addAttribute("name", "iCopper");

        return "hello";
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容