温馨提示×

springboot拦截器怎么创建

小亿
82
2024-01-29 09:24:54
栏目: 编程语言

要创建一个Spring Boot拦截器,你需要按照以下步骤操作:

  1. 创建一个实现HandlerInterceptor接口的类,该接口包含了三个方法,在请求处理过程中会被调用。这三个方法分别是preHandle()postHandle()afterCompletion()。你可以根据需要选择重写其中的一个或多个方法。
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用(Controller方法调用之前)
        return true; // 如果返回false,则请求中断
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要是用于进行资源清理工作)
    }

}
  1. 在Spring Boot应用的配置类中注册拦截器。你可以继承WebMvcConfigurerAdapter类,并重写其中的addInterceptors()方法,将自定义的拦截器添加进去。或者你也可以使用注解@Configuration@EnableWebMvc,然后通过@Override注解重写addInterceptors()方法。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/**");
        // 添加自定义拦截器,并设置拦截路径,这里设置拦截所有请求
    }

}

这样,你就创建了一个简单的Spring Boot拦截器。当请求进入应用时,拦截器的preHandle()方法会被调用,然后根据返回值来决定是否中断请求;在请求处理完成后,拦截器的postHandle()方法会被调用,在视图渲染前执行;最后在整个请求结束后,拦截器的afterCompletion()方法会被调用,进行资源清理。

0