当前位置: 代码迷 >> 综合 >> SpringBoot -> 使用WebMvcConfigurer扩展,拦截器(interceptor),监听器就实现各种listener接口
  详细解决方案

SpringBoot -> 使用WebMvcConfigurer扩展,拦截器(interceptor),监听器就实现各种listener接口

热度:53   发布时间:2023-12-16 09:38:45.0

拦截器:实现接口handlerinterceptor

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
    //url中包含Login就不拦截if (request.getRequestURI().contains("get")) {
    System.out.println("不拦截");return true;}//即url没Login也没登陆,就重新跳转到login.html登陆页面System.out.println("拦截");request.getRequestDispatcher("/index.html").forward(request, response);return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
    }@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex) throws Exception {
    }
}

因为拦截器是spring的所以要在spring配置

与扩展视图一样,都是在webmvcconfigurarer配置注册的
反正就是以前mvc是xml配置,现在是类配置

 @Configuration
public class MyConfiguration implements WebMvcConfigurer {
    @Overridepublic void addInterceptors(InterceptorRegistry registry) {
    //将我们自定义的拦截器加入配置InterceptorRegistration interceptor = registry.addInterceptor(new MyInterceptor());//设置拦截的urlinterceptor.addPathPatterns("/user/**");}
}
  相关解决方案