SpringBoot 拦截器

Spring Boot中的拦截器通常实现HandlerInterceptor接口,该接口定义了三个方法:

  1. preHandle
    在请求处理之前调用。你可以在这里执行诸如验证、日志记录等操作。如果此方法返回false,则请求将不会继续处理。

  2. postHandle
    在请求处理之后但在视图渲染之前调用。你可以在这里对模型数据进行后处理。

  3. afterCompletion
    在整个请求处理完成后调用,即视图渲染之后。你可以在这里执行清理操作。

拦截器流程图:

SpringBoot 拦截器-LMLPHP
要在Spring Boot中使用拦截器,你需要执行以下步骤:

创建拦截器类:

这里以实现登录拦截器为例:

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;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前执行的代码(Controller方法调用之前)
        System.out.println("Pre-handle method is called");
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser == null){
            response.sendRedirect("/user/login");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后执行的代码(Controller方法调用之后)
        System.out.println("Post-handle method is called");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求处理完成后执行的代码(即视图渲染之后)
        System.out.println("After-completion method is called");
    }
}

注册拦截器:

import cn.qvtu.web.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class LoginConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(loginInterceptor);
        registration.addPathPatterns("/user/**"); // 拦截/user下的所有路径
        registration.excludePathPatterns(  // 排除特定路径
                "/user/login",
                "/user/register"
        );
    }
}
04-07 13:20