SpringMVC_03_进阶功能
发布时间:2026/9/28 21:01:38 锦皓数字建站

【Spring MVC】进阶功能拦截器、文件上传与全局异常处理关键词Java、Spring MVC、拦截器、HandlerInterceptor、文件上传、全局异常处理、ControllerAdvice一、拦截器HandlerInterceptor1.1 什么是拦截器拦截器用于在请求到达 Controller之前和之后执行预处理或后处理逻辑。常见场景登录验证、权限检查、日志记录、请求耗时统计。1.2 拦截器生命周期请求进入 ↓ preHandle() ──→ 返回 false请求终止 ↓ (返回 true) Controller 方法执行 ↓ postHandle() ──→ 可以修改 ModelAndView ↓ 视图渲染 ↓ afterCompletion() ──→ 最终回调可获取异常信息1.3 代码示例登录验证拦截器publicclassLoginInterceptorimplementsHandlerInterceptor{OverridepublicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{Objectuserrequest.getSession().getAttribute(loginUser);if(usernull){response.sendRedirect(/login);returnfalse;// 拦截}returntrue;// 放行}OverridepublicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex){if(ex!null){System.out.println(请求异常ex.getMessage());}}}1.4 注册拦截器ConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{OverridepublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(newLoginInterceptor()).addPathPatterns(/**)// 拦截所有.excludePathPatterns(/login,/register,/static/**);}}1.5 拦截器 vs Filter对比项拦截器Interceptor过滤器Filter规范Spring MVC 提供Servlet 规范作用范围只拦截 Controller 请求拦截所有请求含静态资源使用依赖依赖 Spring 容器不依赖 Spring粒度可获取 Handler 信息无法获取 Controller 信息二、文件上传2.1 Controller 处理ControllerpublicclassFileController{PostMapping(/upload)publicStringupload(RequestParam(file)MultipartFilefile,HttpServletRequestrequest)throwsIOException{if(file.isEmpty()){return上传失败文件为空;}StringfileNamefile.getOriginalFilename();StringuploadDirrequest.getServletContext().getRealPath(/uploads/);FiledirnewFile(uploadDir);if(!dir.exists()){dir.mkdirs();}file.transferTo(newFile(dir,fileName));return上传成功fileName;}// 多文件上传PostMapping(/uploadBatch)publicStringuploadBatch(RequestParam(files)MultipartFile[]files){for(MultipartFilefile:files){if(!file.isEmpty()){// 处理每个文件}}return批量上传成功;}}配置Spring Boot 内嵌 Tomcat 默认支持文件上传只需在 yml 中限制大小spring:servlet:multipart:max-file-size:10MBmax-request-size:50MB三、文件下载GetMapping(/download)publicResponseEntitybyte[]download(StringfileName)throwsIOException{StringfilePath/uploads/fileName;byte[]bytesnewFileInputStream(filePath).readAllBytes();HttpHeadersheadersnewHttpHeaders();headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);headers.setContentDispositionFormData(attachment,URLEncoder.encode(fileName,UTF-8));returnnewResponseEntity(bytes,headers,HttpStatus.OK);}四、全局异常处理4.1 为什么要全局异常处理避免每个 Controller 方法都写 try-catch统一异常返回格式区分业务异常和系统异常4.2 ControllerAdvice ExceptionHandlerRestControllerAdvicepublicclassGlobalExceptionHandler{ExceptionHandler(BusinessException.class)publicResulthandleBusinessException(BusinessExceptione){returnResult.error(e.getCode(),e.getMessage());}ExceptionHandler(MethodArgumentNotValidException.class)publicResulthandleValidException(MethodArgumentNotValidExceptione){Stringmessagee.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(, ));returnResult.error(400,message);}ExceptionHandler(Exception.class)publicResulthandleException(Exceptione){e.printStackTrace();returnResult.error(500,服务器内部错误);}}4.3 自定义业务异常publicclassBusinessExceptionextendsRuntimeException{privateintcode;publicBusinessException(intcode,Stringmessage){super(message);this.codecode;}publicintgetCode(){returncode;}}// 使用ServicepublicclassUserService{publicUserfindById(Longid){UseruseruserMapper.selectById(id);if(usernull){thrownewBusinessException(404,用户不存在);}returnuser;}}4.4 ExceptionHandler 优先级优先级说明1精确匹配ExceptionHandler(BusinessException.class)2父类匹配ExceptionHandler(RuntimeException.class)3兜底匹配ExceptionHandler(Exception.class)五、SSM 整合配置总结配置文件职责web.xml配置 DispatcherServlet、ContextLoaderListenerspring-context.xmlService、DAO、事务、数据源spring-mvc.xmlController 扫描、视图解析器、拦截器mybatis-config.xmlMyBatis 配置、Mapper 扫描整合要点Spring 管理 Service/DAOSpring MVC 管理 Controller两个容器通过ContextLoaderListener建立父子关系。六、面试高频问题Q1Spring MVC 拦截器的执行顺序答preHandleController 前→ Controller 方法 → postHandleController 后、视图前→ 视图渲染 → afterCompletion最后执行。如果 preHandle 返回 false后续方法不执行但 afterCompletion 仍会执行。Q2ControllerAdvice 的作用答全局增强注解配合 ExceptionHandler全局异常处理、InitBinder参数绑定、ModelAttribute全局模型数据使用。配合 ResponseBody 变成 RestControllerAdvice直接返回 JSON。Q3Spring MVC 如何处理文件上传答通过 MultipartResolver 解析 multipart 请求。Spring 提供 CommonsMultipartResolver基于 commons-fileupload和 StandardServletMultipartResolver基于 Servlet 3.0。Controller 中用 MultipartFile 接收文件调用 transferTo() 保存。七、总结功能核心类/注解要点拦截器HandlerInterceptorpreHandle / postHandle / afterCompletion文件上传MultipartFile配置 multipart transferTo 保存文件下载ResponseEntity设置 Content-Disposition全局异常ControllerAdvice ExceptionHandler统一异常处理避免重复代码
锦
锦皓数字建站
深耕本土企业品牌数字化升级,专注原创端正雅致商务官网,从视觉设计到稳定运维全程保驾护航。