■ springboot 通过实现HandlerInterceptor接口实现拦截器;
■ 通过实现WebMvcConfigurer接口实现一个配置类,再通过@Configuration注解注入到容器;
■ 指定拦截规则;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 拦截器
* @Author ds
* @Date 2022-06-15
*/
@Component
public class ScanIntercepter implements HandlerInterceptor {
/**
* 预先处理,在目标的controller方法执行之前,进行处理
* true : 通过,继续向下执行
* false : 中止,中断后续操作
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 加入逻辑,比如没有登录返回false;
return true;
}
/**
* 在目标的controller方法执行之后,到达指定页面之前进行处理
*
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/**
* 在页面渲染之后进行处理
*
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
import cn.com.zengxin.common.intercepter.ScanIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置类
* @Author ds
* @Date 2022-06-15
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 除首页和静态资源,全部拦截
*/
registry.addInterceptor(new ScanIntercepter()).addPathPatterns("/**").excludePathPatterns(
"/index", "/static/**"
);
}
}
参考:
https://blog.csdn.net/weixin_52875557/article/details/123793361
网友评论