Spring MVC 框架学习笔记:从入门到精通的实战指南

目录

1. Spring MVC 概述

2. Spring MVC 项目搭建

3. Spring MVC 执行流程

4. Spring MVC @RequestMapping 注解

5. Spring MVC 获取请求参数

6. Spring MVC 常见注解

7. Spring MVC 响应处理

8. Spring MVC SSM 整合

9. Spring MVC 作用域传参

10. Spring MVC 上传

11. Spring MVC 下载

12. Spring MVC 拦截器

13. Spring MVC 异常处理

14. Spring MVC 其他注解

总结


前言

在 Java Web 开发领域,Spring MVC 框架无疑是众多开发者的选择之一。它基于 Spring 框架,提供了强大的 MVC 架构支持,帮助开发者构建高性能、可维护的 Web 应用程序。本文将按照清晰的目录结构,带你深入了解 Spring MVC 的核心概念、功能特性以及实战应用。

1. Spring MVC 概述

Spring MVC 是 Spring 框架的一部分,专门用于构建 Web 应用程序。它遵循 MVC(Model-View-Controller)设计模式,将应用程序分为模型、视图和控制器三个部分,从而实现代码的高内聚和低耦合。

2. Spring MVC 项目搭建

搭建一个 Spring MVC 项目需要以下步骤:

  1. 创建 Maven 项目 :在 IDE 中创建一个新的 Maven 项目,并添加 Spring MVC 的依赖。

xml

<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.10</version>
</dependency>
  1. 配置前端控制器 :在 web.xml 文件中配置 DispatcherServlet,作为前端控制器。

xml

<servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern>
</servlet-mapping>
  1. 配置视图解析器 :在 Spring 配置文件中配置视图解析器,指定视图文件的前缀和后缀。

xml

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"/><property name="suffix" value=".jsp"/>
</bean>

3. Spring MVC 执行流程

Spring MVC 的执行流程如下:

  1. 用户发送请求 :用户通过浏览器发送 HTTP 请求到服务器。

  2. 前端控制器接收请求DispatcherServlet 接收到请求,并将其分发到合适的处理器。

  3. 处理器映射器查找处理器HandlerMapping 查找与请求匹配的处理器(Controller)。

  4. 处理器适配器调用处理器HandlerAdapter 调用处理器方法,并返回 ModelAndView 对象。

  5. 视图解析器解析视图ViewResolver 将视图名称解析为实际的视图对象。

  6. 视图渲染 :视图对象使用模型数据进行渲染,并将结果返回给用户。

4. Spring MVC @RequestMapping 注解

@RequestMapping 是 Spring MVC 中最常用的注解之一,用于将请求映射到处理器方法上。以下是一个简单的示例:

java

@Controller
public class MyController {@RequestMapping("/hello")public String hello() {return "hello";}
}

5. Spring MVC 获取请求参数

Spring MVC 提供了多种方式获取请求参数,包括:

  • 通过方法参数获取 :直接在方法参数中声明需要的参数名称。

java

@Controller
public class MyController {@RequestMapping("/greet")public String greet(@RequestParam("name") String name, Model model) {model.addAttribute("message", "Hello, " + name + "!");return "greet";}
}
  • 通过 @ModelAttribute 获取 :将请求参数绑定到 Java 对象上。

java

@Controller
public class MyController {@RequestMapping("/user")public String getUser(@ModelAttribute("user") User user, Model model) {model.addAttribute("user", user);return "userDetail";}
}

6. Spring MVC 常见注解

Spring MVC 中常用的注解包括:

  • @Controller :标记一个类为控制器。

  • @RequestMapping :将请求映射到处理器方法上。

  • @RequestParam :获取请求参数。

  • @ModelAttribute :绑定请求参数到 Java 对象。

  • @ResponseBody :将方法返回值直接写入响应体。

7. Spring MVC 响应处理

Spring MVC 支持多种响应处理方式,包括:

  • 返回字符串 :返回视图名称,由视图解析器解析为实际视图。

java

@Controller
public class MyController {@RequestMapping("/hello")public String hello() {return "hello";}
}
  • 返回 ModelAndView :包含模型数据和视图信息。

java

@Controller
public class MyController {@RequestMapping("/hello")public ModelAndView hello() {ModelAndView modelAndView = new ModelAndView("hello");modelAndView.addObject("message", "Hello, Spring MVC!");return modelAndView;}
}
  • 返回 JSON 数据 :通过 @ResponseBody 注解返回 JSON 数据。

java

@Controller
public class MyController {@RequestMapping("/user")@ResponseBodypublic User getUser() {User user = new User("John", 30);return user;}
}

8. Spring MVC SSM 整合

SSM(Spring + Spring MVC + MyBatis)是常见的 Java Web 开发框架组合。整合步骤如下:

  1. 添加依赖 :在 pom.xml 中添加 Spring、Spring MVC 和 MyBatis 的依赖。

  2. 配置数据源 :配置数据库连接信息。

xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/test"/><property name="username" value="root"/><property name="password" value="root"/>
</bean>
  1. 配置事务管理器 :配置事务管理器,管理数据库事务。

xml

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/>
</bean>
  1. 配置 MyBatis :配置 MyBatis 的 SqlSessionFactory 和 Mapper。

xml

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

9. Spring MVC 作用域传参

Spring MVC 支持多种作用域传参,包括:

  • 请求作用域(Request Scope) :默认作用域,参数在请求范围内有效。

  • 会话作用域(Session Scope) :参数在会话范围内有效。

java

@Controller
public class MyController {@RequestMapping("/login")public String login(@RequestParam("username") String username, HttpSession session) {session.setAttribute("user", username);return "home";}
}
  • 应用作用域(Application Scope) :参数在应用范围内有效。

10. Spring MVC 上传

Spring MVC 提供了简单的文件上传功能,通过 @RequestParam 注解获取上传的文件对象。

java

@Controller
public class FileController {@PostMapping("/upload")public String upload(@RequestParam("file") MultipartFile file) {try {file.transferTo(new File("path/to/save/" + file.getOriginalFilename()));} catch (IOException e) {e.printStackTrace();}return "uploadSuccess";}
}

11. Spring MVC 下载

Spring MVC 也支持文件下载功能,通过设置响应头和输出流实现。

java

@Controller
public class FileController {@GetMapping("/download")public void download(HttpServletResponse response) {File file = new File("path/to/download/file.txt");response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename=file.txt");try (FileInputStream fis = new FileInputStream(file);OutputStream os = response.getOutputStream()) {byte[] buffer = new byte[1024];int len;while ((len = fis.read(buffer)) > 0) {os.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();}}
}

12. Spring MVC 拦截器

Spring MVC 支持拦截器,用于在请求处理的不同阶段执行特定逻辑。以下是一个简单的拦截器示例:

java

public class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("Pre Handle");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("Post Handle");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("After Completion");}
}

注册拦截器:

xml

<bean class="org.springframework.web.servlet.HandlerInterceptorAdapter"><property name="interceptors"><list><ref bean="myInterceptor"/></list></property>
</bean>

13. Spring MVC 异常处理

Spring MVC 提供了全局异常处理器,通过 @ControllerAdvice 注解实现。

java

@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ModelAndView handleException(Exception e) {ModelAndView modelAndView = new ModelAndView("error");modelAndView.addObject("message", e.getMessage());return modelAndView;}
}

14. Spring MVC 其他注解

Spring MVC 还提供了其他一些有用的注解,如:

  • @InitBinder :用于初始化数据绑定。

java

@Controller
public class MyController {@InitBinderpublic void initBinder(WebDataBinder binder) {binder.setFieldDefaultPrefix("user.");}
}
  • @SessionAttributes :用于将模型属性添加到会话中。

java

@Controller
@SessionAttributes("user")
public class MyController {// ...
}

总结

Spring MVC 作为 Spring 框架的重要组成部分,提供了强大的 Web 开发能力。通过学习 Spring MVC 的核心概念和功能特性,结合实战应用,可以快速构建高性能、可维护的 Web 应用程序。希望本文能够帮助你深入理解 Spring MVC 的精髓,为你的开发工作提供有力支持。如果你有任何问题或建议,欢迎在评论区留言,我们一起交流学习!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/70785.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RK3568开发笔记-AD7616调试笔记

目录 前言 一、AD7616介绍 高分辨率 高速采样速率 宽模拟输入范围 集成丰富功能 二、原理图连接 三、设备树配置 四、内核驱动配置 五、AD芯片测试 总结 前言 在嵌入式数据采集领域,将模拟信号精准转换为数字信号至关重要。AD7616 作为一款性能卓越的 16 位模数转换器…

【对话推荐系统】Towards Topic-Guided Conversational Recommender System 论文阅读

Towards Topic-Guided Conversational Recommender System 论文阅读 Abstract1 Introduction2 Related Work2.1 Conversation System2.2 Conversational Recommender System2.3 Dataset for Conversational Recommendation 3 Dataset Construction3.1 Collecting Movies for Re…

ASP.NET Core 8.0学习笔记(二十八)——EFCore反向工程

一、什么是反向工程 1.原则&#xff1a;DBFirst 2.反向工程&#xff1a;根据数据库表来反向生成实体类 3.生成命令&#xff1a;Scaffold-DbContext ‘连接字符串’ 字符串示例&#xff1a; Server.;DatabaseDemo1;Trusted_Connectiontrue; MultipleActiveResultSets true;Tru…

springcloud和dubbo的区别

Spring Cloud和Dubbo作为微服务架构中非常流行的两个框架&#xff0c;它们在多个方面存在显著的区别。以下是对两者区别的详细分析&#xff1a; 1. 初始定位和生态环境 Spring Cloud&#xff1a;定位为微服务架构下的一站式解决方案&#xff0c;依托于Spring平台&#xff0c;…

【大模型LLM】DeepSeek LLM Scaling Open-Source Language Models with Longtermism

深度探索LLM&#xff1a;以长期主义扩展开源语言模型 0.论文摘要 开源大语言模型&#xff08;LLMs&#xff09;的快速发展确实令人瞩目。然而&#xff0c;以往文献中描述的扩展规律得出了不同的结论&#xff0c;这为LLMs的扩展蒙上了一层阴影。我们深入研究了扩展规律&#…

C#快速调用DeepSeek接口,winform接入DeepSeek查询资料 C#零门槛接入DeepSeek C#接入DeepSeek源代码下载

下载地址<------完整源码 在数字化转型加速的背景下&#xff0c;企业应用系统对智能服务的需求日益增长。DeepSeek作为先进的人工智能服务平台&#xff0c;其自然语言处理、图像识别等核心能力可显著提升业务系统的智能化水平。传统开发模式下&#xff0c;C#开发者需要耗费大…

Qt常用控件之多行输入框QTextEdit

多行输入框QTextEdit QTextEdit 是一个多行输入框控件&#xff0c;支持富文本和 markdown 格式&#xff0c;当文本内容超出编辑框的范围时能自动提供滚动条。 QPlainTextEdit 是只支持富文本格式的多行输入框&#xff0c;属性和使用上与 QTextEdit 几乎没有区别。 QTextEdit属…

VC++零基础入门之系列教程 【附录E MFC快速参考指南】

附录E MFC快速参考指南 E.1 创建窗口 使用M F C CWnd wnd; W n d . C r e a t e E x ( E xSt y l e , C l a s s N a m e , Wi n d o w N a m e , S t y l e , x , y, Wi d t h , H e i g h t , P a r e n t , M e n u , P a r a m ) ; 使用A P I HWND hwnd=::CreateWi n d …

【前端】react+ts 轮播图的实现

一、场景描述 在很多网站的页面中都有轮播图&#xff0c;所以我想利用react.js和ts实现一个轮播图。自动轮播图已经在前面实现过了&#xff0c;如&#xff1a;https://blog.csdn.net/weixin_43872912/article/details/145622444?sharetypeblogdetail&sharerId145622444&a…

python与C系列语言的差异总结(4)

如果具有传统编译型语言的经验&#xff0c;大家可能会对是否使用字典而犹豫不决&#xff0c;担心字典的效率比列表或数组低。事实上Python字典的执行速度已经相当快了。Python语言的许多内部特性都依赖于字典&#xff0c;为提高字典的效率已经投入了大量的心血。Python的所有数…

[Web 安全] 反序列化漏洞 - 学习笔记

关注这个专栏的其他相关笔记&#xff1a;[Web 安全] Web 安全攻防 - 学习手册-CSDN博客 0x01&#xff1a;反序列化漏洞 — 漏洞介绍 反序列化漏洞是一种常见的安全漏洞&#xff0c;主要出现在应用程序将 序列化数据 重新转换为对象&#xff08;即反序列化&#xff09;的过程中…

深入理解C语言中的位段

在C语言编程中&#xff0c;我们常常会遇到需要对内存进行精细控制的场景&#xff0c;位段&#xff08;bit - field&#xff09;便是C语言提供的一种强大工具&#xff0c;它允许我们在一个字节或多个字节内对数据进行按位的定义和操作&#xff0c;极大地提高了内存使用效率。 一…

实现使用RBF(径向基函数)神经网络模拟二阶电机数学模型中的非线性干扰,以及使用WNN(小波神经网络)预测模型中的非线性函数来抵消迟滞影响的功能

下面将详细介绍如何实现使用RBF&#xff08;径向基函数&#xff09;神经网络模拟二阶电机数学模型中的非线性干扰&#xff0c;以及使用WNN&#xff08;小波神经网络&#xff09;预测模型中的非线性函数来抵消迟滞影响的功能。我们将按照以下步骤进行&#xff1a; 步骤1&#x…

Grouped-Query Attention(GQA)详解: Pytorch实现

Grouped-Query Attention&#xff08;GQA&#xff09;详解 Grouped-Query Attention&#xff08;GQA&#xff09; 是 Multi-Query Attention&#xff08;MQA&#xff09; 的改进版&#xff0c;它通过在 多个查询头&#xff08;Query Heads&#xff09;之间共享 Key 和 Value&am…

ReentrantLock 用法与源码剖析笔记

&#x1f4d2; ReentrantLock 用法与源码剖析笔记 &#x1f680; 一、ReentrantLock 核心特性 &#x1f504; 可重入性&#xff1a;同一线程可重复获取锁&#xff08;最大递归次数为 Integer.MAX_VALUE&#xff09;&#x1f527; 公平性&#xff1a;支持公平锁&#xff08;按等…

基于GO语言的车牌识别api技术-港澳车牌文字识别

随着科技的飞速发展&#xff0c;智能化管理逐渐渗透到我们生活的方方面面。车牌识别技术作为智能交通的重要组成部分&#xff0c;不仅极大提升了交通管理的效率&#xff0c;还为市民出行带来了更多便利。而港澳地区的车牌识别技术&#xff0c;凭借其高效、精准、快速的特点&…

基于 DeepSeek LLM 本地知识库搭建开源方案(AnythingLLM、Cherry、Ragflow、Dify)认知

写在前面 博文内容涉及 基于 Deepseek LLM 的本地知识库搭建使用 ollama 部署 Deepseek-R1 LLM知识库能力通过 Ragflow、Dify 、AnythingLLM、Cherry 提供理解不足小伙伴帮忙指正 &#x1f603;,生活加油 我站在人潮中央&#xff0c;思考这日日重复的生活。我突然想&#xff0c…

PCB设计常用布局布线方法

PCB设计常用布局布线方法 **1.模块化布局&#xff0c;**先放大器件再放小器件。 立创在原理图框完后&#xff0c;在PCB快捷shiftp 2.布局对齐美观 3.重要信号线优先处理 分类再画 4.减少Stub布线&#xff1a;就是避免为连接的线段&#xff0c;防止产生“天线效应”&#xff…

Mac 版 本地部署deepseek ➕ RAGflow 知识库搭建流程分享(附问题解决方法)

安装&#xff1a; 1、首先按照此视频的流程一步一步进行安装&#xff1a;(macos版&#xff09;ragflowdeepseek 私域知识库搭建流程分享_哔哩哔哩_bilibili 2、RAGflow 官网文档指南&#xff1a;https://ragflow.io 3、RAGflow 下载地址&#xff1a;https://github.com/infi…

娛閑放鬆篇2

最近看了好多動畫和以前的新聞&#xff0c;都挺有想法&#xff0c;可以了解一下 有些是N年前的&#xff0c;希望見怪莫怪 若說如何用最小作用量去理解世界觀的話&#xff0c;其實就是書&#xff0c;以動畫的角度來看&#xff0c;日本動畫足以 一.高達系列 一系列的利用巨大…