SpringBoot 拦截器

SpringBoot 拦截器

在Spring Boot中,拦截器(Interceptor)是一个强大的工具,它允许你在请求处理之前、之后以及渲染视图之后执行代码。拦截器可以用于执行各种任务,如日志记录、身份验证、授权、数据转换等。

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

  1. preHandle

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

  2. postHandle

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

  3. afterCompletion

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

拦截器流程图:


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

创建拦截器类:

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

java 复制代码
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");
    }
}

注册拦截器:

java 复制代码
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"
        );
    }
}

在上面的配置中,addPathPatterns方法定义了哪些URL路径应该被拦截,而excludePathPatterns方法则定义了哪些路径应该被排除。

拦截器是Spring MVC框架中一个非常强大的特性,通过它你可以对请求处理流程进行细粒度的控制

相关推荐
陌殇殇3 小时前
SpringBoot整合SpringCache缓存
spring boot·redis·缓存
小林学习编程5 小时前
Springboot + vue + uni-app小程序web端全套家具商场
前端·vue.js·spring boot
ladymorgana6 小时前
【Spring boot】tomcat Jetty Undertow对比,以及应用场景
spring boot·tomcat·jetty
IT_10246 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
DCTANT7 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.7 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
喜欢敲代码的程序员9 小时前
SpringBoot+Mybatis+MySQL+Vue+ElementUI前后端分离版:项目搭建(一)
spring boot·mysql·elementui·vue·mybatis
华子w90892585910 小时前
基于 SpringBoot+Vue.js+ElementUI 的 “花开富贵“ 花园管理系统设计与实现7000字论文
vue.js·spring boot·elementui
小时候的阳光10 小时前
SpringBoot3 spring.factories 自动配置功能不生效?
spring boot·spring·失效·factories·imports
大只鹅11 小时前
Springboot3整合ehcache3缓存--XML配置和编程式配置
spring boot·缓存