新闻详情

新闻详情

首页 / 资讯中心 / 详情

SpringMVC_03_进阶功能

发布时间:2026/11/25 0:27:18来源:尧图网络
SpringMVC_03_进阶功能
【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统一异常处理避免重复代码
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/24 21:14:13

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/24 20:34:15

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/24 22:06:24

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/24 9:35:16

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/24 20:27:06

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/24 16:46:36

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉