【拦截器】
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author JHL
* @version 1.0
* @date 2022/9/22 19:30
* @since : JDK 11
*/
public class CustomRequestInterceptor implements HandlerInterceptor {
private static final String[] whiteList = new String[]{
"login",
"isLogin",
};
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag = true;
String url = request.getRequestURI();
for (String s : whiteList) {
if (url.contains(s)) {
flag = false;
}
}
if (flag) {
if ("匹配某种条件就返回false") {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"msg\":\"请求异常!\",\"code\":500}");
response.flushBuffer();
return false;
}
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
【配置拦截器】
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author JHL
* @version 1.0
* @date 2022/9/22 19:41
* @since : JDK 11
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 路径支持正则匹配
registry.addInterceptor(new OpRequestFilter()).addPathPatterns("/path/**");
}
}
标签:SpringBoot,request,springframework,public,import,拦截,servlet,response,请求 From: https://www.cnblogs.com/hhddd-1024/p/16729829.html请求拦截过滤参考:
https://mrbird.cc/Spring-Boot-Filter-Interceptor.html
代码参考: