SpringMVC 基本概念与代码示例

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 {
    @Override
    public 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 {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public 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 文件中:

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. 可能遇到的问题

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 控制器
  • 视图解析
  • 可能遇到的错误及解决方案
相关推荐
懒鸟一枚7 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
我命由我123458 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑8 小时前
Sentinel安装
java·后端·微服务
凤凰院凶涛QAQ10 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
掘金_答案11 小时前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
猿与禅11 小时前
CosId 分布式 ID 生成器完全教程:从架构原理到生产落地
java·shardingsphere·雪花算法·分布式id·高性能·cosid·号段模式
MindUp11 小时前
企业网盘权限模型解析:多层级访问控制与审计能力选型指南
java·linux·运维
NG47711 小时前
【软件设计与体系结构】-策略设计模式
java·设计模式·软件工程
程序员天天困12 小时前
优雅记录操作日志:从注解到 SpEL 的全链路实践与开源方案对比
java·后端
战血石LoveYY12 小时前
Integer类型超限,导致数据异常
java·算法