SpringMVC 基本概念与代码示例

devtools/2025/3/13 22:14:34/

1. SpringMVC 简介

SpringMVC 是 Spring 框架中的一个 Web 层框架,基于 MVC(Model-View-Controller) 设计模式,提供了清晰的分层结构,适用于 Web 应用开发

SpringMVC 主要组件

  1. DispatcherServlet(前端控制器):拦截所有请求并进行分发
  2. HandlerMapping(处理器映射器):确定请求由哪个控制器方法来处理
  3. Controller(控制器):负责处理具体的请求逻辑
  4. ViewResolver(视图解析器):解析视图,渲染最终页面
  5. ModelAndView(模型和视图):封装数据和视图信息

SpringMVC 执行流程

在这里插入图片描述

2. SpringMVC 项目搭建(Spring 6.1.14)

2.1 引入 Maven 依赖

pom.xml 文件中添加以下依赖:

java"><dependencies><!-- Spring Web --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>6.1.14</version></dependency><!-- Servlet API --><dependency><groupId>jakarta.servlet</groupId><artifactId>jakarta.servlet-api</artifactId><version>6.0.0</version><scope>provided</scope></dependency><!-- Jackson 用于 JSON 解析 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.16.0</version></dependency>
</dependencies>

2.2 配置 SpringMVC(Java 配置方式)

2.2.1 Web 初始化配置

使用 WebApplicationInitializer 代替 web.xml,实现 SpringMVC 自动初始化

java">import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;public class WebAppInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.register(SpringMvcConfig.class);ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));dispatcher.setLoadOnStartup(1);dispatcher.addMapping("/*");}
}
2.2.2 SpringMVC 配置类
java">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;@Configuration
@EnableWebMvc
@ComponentScan("com.alivinfer.controller")
public class SpringMvcConfig implements WebMvcConfigurer {@Beanpublic ViewResolver viewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix("/WEB-INF/views/");resolver.setSuffix(".jsp");return resolver;}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("/static/");}
}

2.3 创建 Controller 处理请求

java">import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/user")
public class UserController {@GetMapping("/hello")public String sayHello() {return "Hello, SpringMVC!";}
}

2.4 创建 JSP 视图

webapp/WEB-INF/views/hello.jsp 文件中:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head><title>Hello SpringMVC</title>
</head>
<body><h2>Hello, SpringMVC</h2>
</body>
</html>

3. 运行与测试

  1. 启动 Tomcat 或其他 Servlet 容器
  2. 访问 http://localhost:8080/user/hello,返回 Hello, SpringMVC!
  3. 访问 http://localhost:8080/hello.jsp,查看 JSP 视图

4. 可能遇到的问题

javautilLinkedHashSet_147">4.1 NoSuchMethodError: java.util.LinkedHashSet

如果运行时报 java.util.LinkedHashSet 相关错误,可能是 Spring 版本与 Jakarta 依赖不兼容,请检查以下内容:

  • Spring 6+ 需要 Jakarta EE 9+,务必使用 **jakarta.servlet-api 6.0.0+**
  • 确保 spring-webmvcspring-context 版本一致

4.2 404 Not Found

  • 检查 WebAppInitializer 是否正确注册了 DispatcherServlet
  • 确保 @ComponentScan 扫描到了 Controller
  • 试试清理项目 mvn clean,然后 mvn package 重新部署

5. 总结

本文主要介绍了 SpringMVC 的基本概念,并基于 Spring 6.1.14 搭建了一个简单的 MVC 应用,包括:

  • Maven 依赖
  • DispatcherServlet 配置
  • Controller 控制器
  • 视图解析
  • 可能遇到的错误及解决方案

http://www.ppmy.cn/devtools/166865.html

相关文章

不同AI生成的PHP版雪花算法

OpenAI <?php /*** Snowflake 雪花算法生成器* 生成的 64 位 ID 结构&#xff1a;* 1 位 保留位&#xff08;始终为0&#xff0c;防止负数&#xff09;* 41 位 时间戳&#xff08;毫秒级&#xff0c;当前时间减去自定义纪元&#xff09;* 5 位 数据中心ID* 5 …

每天一篇《目标检测》文献(一)

今天看的是《改进 YOLOv8 的轻量化密集行人检测方法》。 目录 一、摘要 二、背景介绍 三、YOLOv8介绍 四 改进结构介绍 4.1 双卷积内核&#xff08;DualConv&#xff09; 4.2 RS-C2f模块 4.3 空间金字塔池化改进&#xff08;SPPELAN_BiFPN&#xff09; 4.4 损失函数优化…

SIP 协议详解:原理、用途与应用场景

1. SIP 协议简介 SIP&#xff08;Session Initiation Protocol&#xff0c;会话初始化协议&#xff09;是一个应用层协议&#xff0c;属于计算机网络的七层模型&#xff08;OSI 模型&#xff09;中的第七层。在计算机网络中&#xff0c;OSI 参考模型将网络通信划分为以下 7 层…

大话机器学习三大门派:监督、无监督与强化学习

以武侠江湖为隐喻&#xff0c;系统阐述了机器学习的三大范式&#xff1a;​监督学习&#xff08;少林派&#xff09;​凭借标注数据精准建模&#xff0c;擅长图像分类等预测任务&#xff1b;无监督学习&#xff08;逍遥派&#xff09;​通过数据自组织发现隐藏规律&#xff0c;…

Git 的详细介绍及用法

一、Git 的优点 分布式版本控制 每个开发者都拥有完整的仓库副本&#xff0c;无需依赖中央服务器&#xff08;如 SVN&#xff09;。支持离线操作&#xff08;提交、查看历史、创建分支等&#xff09;。 高效的分支管理 创建和切换分支速度快&#xff08;几乎是瞬间完成&#x…

【每日五题系列】前端面试高频题目

比如防抖、节流、深度优先遍历和广度优先遍历的实现&#xff0c;还有Promise、async/await这些。 提到了数组扁平化、Localstorage缓存系统设计、ES6模板语法。数组扁平化是一个常见的手写题&#xff0c;应该加入。缓存系统设计可能比较复杂&#xff0c;但作为设计题也是常考的…

生成对抗网络(GAN)原理与应用

目录 一、引言 二、GAN的基本原理 &#xff08;一&#xff09;生成器&#xff08;Generator&#xff09;的工作机制 &#xff08;二&#xff09;判别器&#xff08;Discriminator&#xff09;的工作机制 &#xff08;三&#xff09;对抗训练的过程 三、GAN在AIGC生图中的应…

GC安全点导致停顿时间过长的案例

GC安全点导致停顿时间过长的案例 前言安全点的概念案例分析解决方法如有需要收藏的看官&#xff0c;顺便也用发财的小手点点赞哈&#xff0c;如有错漏&#xff0c;也欢迎各位在评论区评论&#xff01; 前言 前段时间在使用G1垃圾收集时&#xff0c;因服务读写压力过大&#xf…