把大象放冰箱里,总共分两步:
一、自定义一个拦截器
二、注册拦截器
================分割线===========================================
一:自定义拦截器
package com.company.giants.interceptors;
import com.company.giants.annotation.JustTest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class CopInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 根据业务需求,操作request、response、handler
// 举例:拦截JustTest注解,打印:拦截器操作了
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 判断是否存在JustTest注解
JustTest justTest = handlerMethod.getMethodAnnotation(JustTest.class);
if (justTest != null && StringUtils.isNotBlank(justTest.value())) {
log.info("拦截器操作了");
}
}
return true;
}
}
二:注册拦截器
package com.company.giants.config;
import com.company.giants.interceptors.CopInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CopInterceptor()).addPathPatterns("/**")
// login、fonts除外
.excludePathPatterns("/login", "/fonts/**");
}
}
结束。就这么简单。
===============补充说明==========================
拦截器中的excludePathPatterns("/login"),括号中的参数,要跟context-path后严格一致,后面如果加 /** ,说明包括子目录。举例如下:
http://localhost:8090/mod-test/just/login
其中context-path:/mod-test
excludePathPatterns("/login/**")
会将下面两个都除外(不会拦截):
http://localhost:8090/mod-test/login
http://localhost:8090/mod-test/login/test
下面这个则不会除外(会拦截):