当前位置: 首页 > news >正文

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 文件中添加以下依赖:

<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 自动初始化

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 配置类
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 处理请求

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

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.mrgr.cn/news/93953.html

相关文章:

  • 【git】 贮藏 stash
  • 《 C++ 点滴漫谈: 三十 》高手写 C++,参数这样传才高效!你真的用对了吗?
  • 【git】删除已加入 .gitignore却仍被git追踪的文件
  • 1分钟看懂React的那些Hook‘s
  • java每日精进 3.11 【多租户】
  • 【性能测试】Jmeter详细操作-小白使用手册(2)
  • win10安装部署DB-gpt,坑多
  • 【Linux docker】关于docker启动出错的解决方法。
  • git规范提交之commitizen conventional-changelog-cli 安装
  • cu118 安装vllm 极简教程 踩坑笔记
  • [pytest] 配置
  • 【08】单片机编程核心技巧:变量命名规范
  • DeepSeek大语言模型下几个常用术语
  • 创建Electron35 + vue3 + electron-builder项目,有很过坑,记录过程
  • 【模拟CMOS集成电路设计】带隙基准(Bandgap)设计与仿真(基于运放的电流模BGR)
  • 从0开始的操作系统手搓教程43——实现一个简单的shell
  • 【SpringMVC】深入解析@ RequestMapping 注解的概念及使用和 MVC 介绍
  • QT多线程
  • 代码随想录刷题day41|(二叉树篇)二叉树的最大深度(递归)
  • 【前端】BOM DOM