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
控制器- 視圖解析
- 可能遇到的錯誤及解決方案