ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

SpringBoot工程使用拦截器详解

SpringBoot工程使用拦截器详解 在Spring Boot工程中拦截器Interceptor是一种强大的工具用于在请求处理的前后执行特定的逻辑。拦截器可以对请求进行预处理和后处理例如身份验证、日志记录、性能监控等。拦截器实现实现HandlerInterceptor接口自定义拦截器需要实现org.springframework.web.servlet.HandlerInterceptor接口该接口包含三个方法preHandle在请求处理之前执行返回true表示继续执行后续的处理流程返回false则中断请求处理。postHandle在请求处理之后、视图渲染之前执行。afterCompletion在整个请求处理完成后执行通常用于资源清理等操作。注册拦截器需要将自定义的拦截器注册到 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.customInterceptorcustomInterceptor;}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{HttpSessionsessionrequest.getSession();Objectusersession.getAttribute(user);if(usernull){// 用户未登录重定向到登录页面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.authenticationInterceptorauthenticationInterceptor;}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{StringBuilderrequestParamsnewStringBuilder();EnumerationStringparamNamesrequest.getParameterNames();while(paramNames.hasMoreElements()){StringparamNameparamNames.nextElement();StringparamValuerequest.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.loggingInterceptorloggingInterceptor;}OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(loggingInterceptor).addPathPatterns(/**);// 拦截所有请求}}
RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进