Spring MVC(Model-View-Controller)是 Spring 框架中用于构建 Web 应用的模块,它实现了基于模型-视图-控制器(MVC)设计模式的 Web 应用程序开发。MVC 模式通过将应用逻辑、数据和界面分开,促进应用的分层设计:
Spring MVC 是构建 Java Web 应用程序的常用工具,提供了灵活的、可扩展的结构,支持多种视图技术,如 JSP、Thymeleaf、FreeMarker 等。
为了理解 Spring MVC 的基本概念,下面通过一个简单的入门示例程序展示其工作原理。
SpringMVC-Example
│ pom.xml
└───src
└───main
├───java
│ └───com
│ └───example
│ ├───controller
│ │ HomeController.java
│ └───config
│ WebConfig.java
└───webapp
├───WEB-INF
│ web.xml
│ views
│ └───home.jsp
1. pom.xml
<dependencies>
<!-- Spring MVC 依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!-- JSP 支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
2. web.xml
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
</web-app>
3. HomeController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@RequestMapping("/")
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("home");
modelAndView.addObject("message", "欢迎来到Spring MVC世界!");
return modelAndView;
}
}
4. WebConfig.java
package com.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {
}
5. home.jsp
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
Spring MVC 的工作流程可以概括为以下几个步骤: