自学内容网 自学内容网

拦截器获取controller上的自定义注解

拦截器获取controller上的注解

RateLimit 为自定义注解

          if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method != null) {
                //获取方法上的注解
                RateLimit myannoaction = method.getMethodAnnotation(RateLimit.class);

            }
        }

完整示例

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle 我在方法执行前面执行 " + System.currentTimeMillis());
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method != null) {
                //获取方法上的注解
                RateLimit myannoaction = method.getMethodAnnotation(RateLimit.class);

            }
        }
        return true; //返回true才能继续往下
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle (没发生异常的情况下)我在方法执行完后执行 " + System.currentTimeMillis());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion 不管方法是否发生异常,我都在完成后执行 " + System.currentTimeMillis());
    }
}

传送门

springboot基础(59):自定义拦截器


原文地址:https://blog.csdn.net/u011628753/article/details/143575621

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!