SpringBoot工程使用拦截器详解

SpringBoot工程使用拦截器详解

在Spring Boot工程中,拦截器(Interceptor)是一种强大的工具,用于在请求处理的前后执行特定的逻辑。拦截器可以对请求进行预处理和后处理,例如身份验证、日志记录、性能监控等。

拦截器实现
  1. 实现HandlerInterceptor接口:自定义拦截器需要实现org.springframework.web.servlet.HandlerInterceptor接口,该接口包含三个方法:

    • preHandle:在请求处理之前执行,返回true表示继续执行后续的处理流程,返回false则中断请求处理。
    • postHandle:在请求处理之后、视图渲染之前执行。
    • afterCompletion:在整个请求处理完成后执行,通常用于资源清理等操作。
  2. 注册拦截器:需要将自定义的拦截器注册到 Spring MVC 的拦截器链中。可以通过实现WebMvcConfigurer接口,并重写addInterceptors方法来完成注册。

代码示例
importorg.springframework.stereotype.Component;importorg.springframework.web.servlet.HandlerInterceptor;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;// 自定义拦截器@ComponentpublicclassCustomInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{System.out.println("请求处理前执行,URL: "+request.getRequestURI());// 可以在此进行身份验证等操作returntrue;}@OverridepublicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,org.springframework.web.servlet.ModelAndViewmodelAndView)throwsException{System.out.println("请求处理后、视图渲染前执行");}@OverridepublicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{System.out.println("整个请求处理完成后执行");}}importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;// 配置拦截器@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{privatefinalCustomInterceptorcustomInterceptor;publicWebConfig(CustomInterceptorcustomInterceptor){this.customInterceptor=customInterceptor;}@OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(customInterceptor).addPathPatterns("/**")// 拦截所有请求.excludePathPatterns("/public/**");// 排除某些请求}}
身份验证的实现

在电商系统中,很多业务操作需要用户进行身份验证,例如查看订单、下单等。可以使用拦截器在请求处理前检查用户的登录状态,如果用户未登录,则重定向到登录页面。

代码示例
importorg.springframework.stereotype.Component;importorg.springframework.web.servlet.HandlerInterceptor;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;// 身份验证拦截器@ComponentpublicclassAuthenticationInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{HttpSessionsession=request.getSession();Objectuser=session.getAttribute("user");if(user==null){// 用户未登录,重定向到登录页面response.sendRedirect("/login");returnfalse;}returntrue;}}importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;// 配置身份验证拦截器@ConfigurationpublicclassAuthWebConfigimplementsWebMvcConfigurer{privatefinalAuthenticationInterceptorauthenticationInterceptor;publicAuthWebConfig(AuthenticationInterceptorauthenticationInterceptor){this.authenticationInterceptor=authenticationInterceptor;}@OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(authenticationInterceptor).addPathPatterns("/orders/**","/checkout/**");// 拦截订单和结算相关的请求}}
日志记录

在电商系统中,记录用户的请求日志有助于后续的问题排查和数据分析。可以使用拦截器在请求处理前后记录相关信息,例如请求的 URL、请求参数、处理时间等。

代码示例
importorg.springframework.stereotype.Component;importorg.springframework.web.servlet.HandlerInterceptor;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.Enumeration;// 日志记录拦截器@ComponentpublicclassLoggingInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{StringBuilderrequestParams=newStringBuilder();Enumeration<String>paramNames=request.getParameterNames();while(paramNames.hasMoreElements()){StringparamName=paramNames.nextElement();StringparamValue=request.getParameter(paramName);requestParams.append(paramName).append("=").append(paramValue).append("&");}if(requestParams.length()>0){requestParams.deleteCharAt(requestParams.length()-1);}System.out.println("请求 URL: "+request.getRequestURI()+", 请求参数: "+requestParams.toString());returntrue;}@OverridepublicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{System.out.println("请求处理完成,状态码: "+response.getStatus());}}importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;// 配置日志记录拦截器@ConfigurationpublicclassLoggingWebConfigimplementsWebMvcConfigurer{privatefinalLoggingInterceptorloggingInterceptor;publicLoggingWebConfig(LoggingInterceptorloggingInterceptor){this.loggingInterceptor=loggingInterceptor;}@OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(loggingInterceptor).addPathPatterns("/**");// 拦截所有请求}}