900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Spring拦截器(实现自定义注解)

Spring拦截器(实现自定义注解)

时间:2019-01-28 09:15:14

相关推荐

Spring拦截器(实现自定义注解)

一、定义注解类

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Authority {String[] value() default {""}}

二、定义控制器

@Controllerpublic class UserController {@GetMapping("/test")@Authority("")public String welcome() {return "welcome";}}

三、定义自定义拦截器

public class MyFirstInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HandlerMethod handlerMethod = (HandlerMethod)handler;Authority authority = handlerMethod.getMethod().getAnnotation(Authority.class);if(authority != null) {System.out.println(authority.value());System.out.println("处理器方法执行之前调用 → preHandle");return true;}return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {//System.out.println("处理器方法执行之后调用 → postHandle");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// System.out.println("页面显示完毕之后调用 → afterCompletion");}}

四、配置拦截器

@Configurationpublic class MyConfig implements WebMvcConfigurer {@Beanpublic MyFirstInterceptor myFirstInterceptor() {new MyFirstInterceptor();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {//注册TestInterceptor拦截器InterceptorRegistration registration = registry.addInterceptor(new MyFirstInterceptor());/* 所有路径都被拦截 */// registration.addPathPatterns("/**");}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。