Springboot配置拦截器

和springmvc大致相同,也是拦截器类实现interector接口,不同是用一个类来代替springmvc.xml,该类要实现WebMvcConfigurer接口,作为springmvc的配置类。

和springmvc的拦截器一样,其实就是springmvc的拦截器

springmvc拦截器_仰望星空的快乐的博客-CSDN博客_springmvc 配置拦截器

 拦截除了 /  和  /index的所有请求

package com.example.springbootdemo3.config;

import com.example.springbootdemo3.testfilter.firstInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

//代替原来的springmvc.xml文件,实现springmvc的自动化配置
//可以配置 视图解析器  拦截器 文件上传解析器  注解驱动 异常处理  组件扫描范围
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
//    registry是整个拦截器的注册中心
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new firstInterceptor())
               .addPathPatterns("/**")
               .excludePathPatterns("/","/index");
   }
}
package com.example.springbootdemo3.testfilter;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//1.设置拦截器实现handlerinterceptor接口,写拦截方法
//2.在spring的doInterceptors方法中添加该控制器
public class firstInterceptor implements HandlerInterceptor {
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      System.out.println("拦截器拦截了");
      HttpSession session= request.getSession();
     if(session.getAttribute("user")==null)
     { System.out.println("拦截器跳转了");
        response.sendRedirect("index");
     }
        return true;
    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    System.out.println("posthandel执行了");
   }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("afterhandle执行了");
   }
}

不一样的地方:如果在拦截器返回true而且重定向或者请求转发了,则会使用重定向或者请求转发的路径,可以跳转,但是会控制台报错

2022-06-10 18:39:56.231 ERROR 17116 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendError() after the response has been committed] with root cause

 Springboot配置拦截器_第1张图片

 

你可能感兴趣的:(spring-boot,spring,boot,java,spring)