Spring MVC 入门与高级用法
大约 3 分钟
Spring MVC 入门与高级用法
Spring MVC(Model-View-Controller)是 Spring 框架的一部分,用于构建基于 Web 的应用程序。它提供了一整套用于处理 HTTP 请求和响应的功能,并通过注解简化了配置。本文将介绍 Spring MVC 的基本用法和一些高级特性。
1. Spring MVC 基本用法
1.1 添加依赖
首先,在项目中添加 Spring MVC 的依赖。以 Maven 为例,在 pom.xml
文件中添加以下内容:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- 其他依赖,例如 Spring Core、Spring Context 等 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
1.2 配置 Spring MVC
web.xml
传统的基于 XML 的配置方式,首先需要在 web.xml
中配置 Spring MVC 的 DispatcherServlet:
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.xml
创建 Spring MVC 的配置文件 spring-servlet.xml
:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.example.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
1.3 创建控制器
HelloController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring MVC!");
return "hello";
}
}
1.4 创建视图
在 WEB-INF/views
目录下创建 hello.jsp
文件:
<!-- hello.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
1.5 运行应用
将项目部署到支持 Servlet 容器的服务器(例如 Tomcat),启动服务器后,访问 http://localhost:8080/hello 即可看到页面显示 "Hello, Spring MVC!"。
2. Spring MVC 高级用法
2.1 表单处理
User.java
创建一个简单的表单数据对象:
package com.example.model;
public class User {
private String name;
private String email;
// Getters and Setters
}
UserController.java
处理表单提交的控制器:
package com.example.controller;
import com.example.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
@GetMapping("/userForm")
public String userForm(Model model) {
model.addAttribute("user", new User());
return "userForm";
}
@PostMapping("/submitForm")
public String submitForm(@ModelAttribute User user, Model model) {
model.addAttribute("user", user);
return "userView";
}
}
创建视图
在 WEB-INF/views
目录下创建 userForm.jsp
和 userView.jsp
文件:
userForm.jsp
<!-- userForm.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>User Form</title>
</head>
<body>
<form action="submitForm" method="post">
Name: <input type="text" name="name"/><br/>
Email: <input type="text" name="email"/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
userView.jsp
<!-- userView.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>User View</title>
</head>
<body>
<h1>User Information</h1>
<p>Name: ${user.name}</p>
<p>Email: ${user.email}</p>
</body>
</html>
2.2 异常处理
Spring MVC 提供了几种异常处理方式,包括使用 @ExceptionHandler
注解和 @ControllerAdvice
注解。
使用 @ExceptionHandler
package com.example.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
@Controller
public class ErrorController {
@GetMapping("/causeError")
public String causeError() {
throw new RuntimeException("Test Exception");
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleRuntimeException(RuntimeException ex, Model model) {
model.addAttribute("message", ex.getMessage());
return "error";
}
}
创建视图
在 WEB-INF/views
目录下创建 error.jsp
文件:
<!-- error.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Error Occurred</h1>
<p>${message}</p>
</body>
</html>
2.3 文件上传
Spring MVC 通过 MultipartFile
接口支持文件上传。
添加依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
配置文件上传解析器
在 spring-servlet.xml
中添加配置:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
文件上传控制器
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class FileUploadController {
private static String UPLOAD_DIR = "uploads/";
@GetMapping("/upload")
public String uploadForm() {
return "uploadForm";
}
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload.");
return "redirect:uploadStatus";
}
try {
// 保存文件到本地
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "upload