天天看點

Spring攔截器(實作自定義注解)一、定義注解類二、定義控制器三、定義自定義攔截器四、配置攔截器

一、定義注解類

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

二、定義控制器

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

三、定義自定義攔截器

public class MyFirstInterceptor implements HandlerInterceptor {
    @Override
    public 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;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("處理器方法執行之後調用 → postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // System.out.println("頁面顯示完畢之後調用 → afterCompletion");
    }
}
           

四、配置攔截器

@Configuration
public class MyConfig implements WebMvcConfigurer {
	@Bean
	public MyFirstInterceptor myFirstInterceptor() {
		new MyFirstInterceptor();
	}
	
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注冊TestInterceptor攔截器
        InterceptorRegistration registration = registry.addInterceptor(new MyFirstInterceptor());
        /* 所有路徑都被攔截 */
        // registration.addPathPatterns("/**");
}