SpringMVC 基本概念与代码示例
1. SpringMVC 简介
SpringMVC 是 Spring 框架中的一个 Web 层框架,基于 MVC(Model-View-Controller) 设计模式,提供了清晰的分层结构,适用于 Web 应用开发
SpringMVC 主要组件
- DispatcherServlet(前端控制器):拦截所有请求并进行分发
- HandlerMapping(处理器映射器):确定请求由哪个控制器方法来处理
- Controller(控制器):负责处理具体的请求逻辑
- ViewResolver(视图解析器):解析视图,渲染最终页面
- 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. 运行与测试
- 启动 Tomcat 或其他 Servlet 容器
- 访问
http://localhost:8080/user/hello
,返回Hello, SpringMVC!
- 访问
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-webmvc
和spring-context
版本一致
4.2 404 Not Found
- 检查
WebAppInitializer
是否正确注册了DispatcherServlet
- 确保
@ComponentScan
扫描到了Controller
- 试试清理项目
mvn clean
,然后mvn package
重新部署
5. 总结
本文主要介绍了 SpringMVC 的基本概念,并基于 Spring 6.1.14 搭建了一个简单的 MVC 应用,包括:
- Maven 依赖
DispatcherServlet
配置Controller
控制器- 视图解析
- 可能遇到的错误及解决方案