1,定义拦截器
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@Componentpublic class AuthorityInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(AuthorityInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("进入到拦截器中:preHandle() 方法"); HandlerMethod handlerMethod=(HandlerMethod)handler; AccessIntercept loginVerify=handlerMethod.getMethodAnnotation(AccessIntercept.class); if (loginVerify!=null){ System.out.println(loginVerify.IsIntercept()); logger.info("不需要对 @loginVerify注解方法 进行拦截"); return false; }else { logger.info("对非@loginVerify注解方法 进行拦截处理"); System.out.println(request.getServletPath()); System.out.println(request.getParameter("id")); return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("进入到拦截器中:postHandle() 方法中"); System.out.println(request.getRequestURI()); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("进入到拦截器中:afterCompletion() 方法中"); System.out.println(request.getServletPath()); }}
2,配置拦截器
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class InterceptorAdapterConfig extends WebMvcConfigurerAdapter { @Autowired// private RequestLimitIntercept authorityInterceptor; private AuthorityInterceptor authorityInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //注册自己的拦截器并设置拦截的请求路径 registry.addInterceptor(authorityInterceptor).addPathPatterns("/**"); super.addInterceptors(registry); }}
3,自定义注解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface AccessIntercept { boolean IsIntercept() default true;}
4,使用自定义注解
在controller中的方法上面使用@AccessIntercept注解。