3. 动作模型
动作需要浏览器发送的信息:URL 的参数([?name=martin&age=42])、表单字段、JSON 请求体,有时还有一个 HTTP 请求头。原课程把这组信息统称 为动作的模型。本章展示 [Spring MVC] 如何把这些信息提供给动作、把它们转换为正确的类型并加以验证。这一过程称为 数据绑定 ([data binding])。
术语说明:在 [Spring MVC] 中,“模型”([Model])一词主要指动作传递给其视图的数据(第 4 章“视图及其模型”)。本章所说的动作的模型,则是它 接收的内容。
示例 07 至 12 与上一章的示例一样,都是文件夹 [Maven] [examples] 中的模块。你可以在该文件夹中打开终端并输入 [../mvnw spring-boot:run](在 [..\mvnw spring-boot:run] 下为 [Windows])来运行其中一个;[Ctrl-C] 停止服务器。每个示例都有一个名为 [application.properties] 的文件,内容类似下面这样:
| # 服务器的监听端口(默认为 8080)
server.port=5000
# Spring Boot 的错误响应不包含调用栈
spring.web.error.include-stacktrace=never
|
- 第 2 行:服务器的监听端口;
- 第 4 行:请求失败时,[Spring Boot] 会用一个 JSON 错误文档作出响应(本章中我们会看到许多这样的文档)。这个属性使异常的调用栈([stack trace])——它很长,绝不应向用户显示——不会被包含在内。这样做是必要的,因为 [spring-boot-devtools] 依赖(开发工具,在父级 [pom.xml] 中声明)会在开发期间更改若干默认设置:特别是,它会把异常消息(属性 [spring.web.error.include-message])和调用栈([spring.web.error.include-stacktrace])加入这个 JSON。我们保留消息,因为它有助于理解发生了什么;在生产环境中,没有开发工具时,它也会消失。
3.1. 示例 07:URL 的参数
[controllers/ParametersController.java] 文件:
| package example07.controllers;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/parameters")
public class ParametersController {
// /parameters/action01?name=martin:URL 参数 [name] -> 操作参数 [name]
// required = false:参数可以缺失,此时为 null
@GetMapping("/action01")
public String action01(@RequestParam(required = false) String name) {
return "name = [%s], of type %s".formatted(name, name == null ? "null" : name.getClass().getSimpleName());
}
// /parameters/action02?age=42:值会被转换为参数的类型;
// 没有 required = false 时,该参数是必需的
@GetMapping("/action02")
public String action02(@RequestParam int age) {
return "age = [%d], of type int".formatted(age);
}
// /parameters/action03?age=42:Integer(而不是 int)接受 null 值
@GetMapping("/action03")
public String action03(@RequestParam(required = false) Integer age) {
return "age = [%s]".formatted(age);
}
// /parameters/action04?page=2:参数缺失时使用默认值
@GetMapping("/action04")
public String action04(@RequestParam(defaultValue = "1") int page) {
return "page = [%d]".formatted(page);
}
// /parameters/action05?q=spring:当 URL 参数的名称不同时,指定该名称
@GetMapping("/action05")
public String action05(@RequestParam(name = "q", required = false) String search) {
return "search = [%s]".formatted(search);
}
// /parameters/action06?name=martin&age=42:一次获取所有参数
@GetMapping("/action06")
public Map<String, String> action06(@RequestParam Map<String, String> parameters) {
return parameters;
}
}
|
我们来说明这段代码:
- 第 16–17 行:注解 [@RequestParam] 把动作的一个参数与 URL 的一个参数([?] 后面的部分,称为查询字符串,即 [query string])关联起来。除非另有指定,URL 中的参数与 同名 ,即 [Java] 中的参数名:[name]。这个名称在运行时之所以可知,仅仅是因为 [Spring Boot] 的父项目指示编译器在编译后的代码中保留它(选项 [-parameters])。注解可以接受具名参数,称为 属性:[required = false] 表示该参数可以省略;此时它等同于 [null]。第 18 行:方法 [formatted] 用后面的参数替换字符串 [%s] 中 的每一处;[name.getClass().getSimpleName()] 是该值所属类型的简短名称;
- 第 23–24 行:该参数被声明为类型 [int]:[Spring MVC] 会把 收到的字符串(["42"])转换成数字。如果没有 [required = false] 属性,[@RequestParam] 会使该参数成为 必需的:这是 [required] 的默认值。缺少参数,或者参数转换失败,都会导致 400 错误,并且不会执行动作;
- 第 29–30 行:[int] 不可能等于 [null]。对于可选的数字,参数要声明为类型 [Integer],即 [Java] 的类,它“包装”一个 [int] ([wrapper]):[Integer] 对象可以取值 [null],这样就能区分“没有年龄”和“年龄为 0”;
- 第 35–36 行:[defaultValue] 属性提供参数缺失时使用的值(它同时也使该参数成为可选的)。它是一个字符串,转换方式与收到的值相同;
- 第 41–42 行:当 URL 的参数名与 [name] 参数名不同时,属性 [Java] 用来指定 URL 参数的名称:动作的 [search] 参数接收 URL 中的 [q] 参数;
- 第 47–48 行:标注了 [Map<String, String>] 类型的 [@RequestParam] 参数会接收 所有 URL 参数,不做转换:一个字典(参数名,值)。动作原样返回它,由 [Spring MVC] 把它序列化为 JSON。
结果如下:
| curl -i "http://localhost:5000/parameters/action01?name=martin"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 31
name = [martin], of type String
|
| curl -i "http://localhost:5000/parameters/action01"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 27
name = [null], of type null
|
[Tomcat] 服务器不会在第一行的 200 状态码之后输出文本 [OK] :这个文本在 HTTP/1.1 中是可选的;只有状态码才重要。当 URL 包含字符 [&] 时,必须给 URL 加上引号,因为该字符对控制台有特殊含义;我们在所有地方都加了引号。类型为 [int] 的参数:
| curl -i "http://localhost:5000/parameters/action02?age=42"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 23
age = [42], of type int
|
| curl -i "http://localhost:5000/parameters/action02?age=abc"
|
| HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-09-25T16:46:05.177Z","status":400,"error":"Bad Request","message":"Method parameter 'age': Failed to convert value of type 'java.lang.String' to required type 'int'; For input string: \"abc\"","path":"/parameters/action02"}
|
| curl -i "http://localhost:5000/parameters/action02"
|
| HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-09-25T16:46:05.205Z","status":400,"error":"Bad Request","message":"Required parameter 'age' is not present.","path":"/parameters/action02"}
|
这与 [ASP.NET Core MVC] 有显著区别,后者在无法转换时并不阻止动作的执行。使用 [@RequestParam] 时,[Spring MVC] 会在调用动作之前抛出异常:转换不可能时抛出 [MethodArgumentTypeMismatchException] ,缺少必需参数时抛出 [MissingServletRequestParameterException] (服务器控制台会显示这些异常的名称)。[Spring MVC] 的一个组件把它们转换为 400 错误响应([Bad Request],即无效请求),而 [Spring Boot] 生成该响应的响应体:这就是上一章已经遇到过的 JSON 错误响应。它的字段有:
- [timestamp]:错误发生的日期和时间(采用协调世界时);
- [status]、[error]:HTTP 状态码及其描述;
- [message]:异常消息,之所以包含在这里,是因为开发工具要求如此;
- [path]:请求路径。
请求 HTML 页面的浏览器则会收到一个最简的错误页面——“Whitelabel Error Page”。我们将在示例 12 中看到如何自己处理这些异常。对于类型 [Integer]:
| curl -i "http://localhost:5000/parameters/action03?age=42"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 10
age = [42]
|
| curl -i "http://localhost:5000/parameters/action03"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 12
age = [null]
|
| curl -i "http://localhost:5000/parameters/action03?age=abc"
|
| HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-09-25T16:46:05.250Z","status":400,"error":"Bad Request","message":"Method parameter 'age': Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; For input string: \"abc\"","path":"/parameters/action03"}
|
缺失的参数被视为 [null];无效的参数则始终导致 400 错误。默认值:
| curl -i "http://localhost:5000/parameters/action04"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 10
page = [1]
|
| curl -i "http://localhost:5000/parameters/action04?page=2"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 10
page = [2]
|
| curl -i "http://localhost:5000/parameters/action04?page="
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 10
page = [1]
|
存在但为空的参数([?page=])被视为缺失:它取默认值。最后两个动作:
| curl -i "http://localhost:5000/parameters/action05?q=spring"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 17
search = [spring]
|
| curl -i "http://localhost:5000/parameters/action06?name=martin&age=42"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 28
{"name":"martin","age":"42"}
|
这里 age 是一个字符串(["42"]):由于没有声明类型,也就没有转换。最后,参数名 区分大小写:
| curl -i "http://localhost:5000/parameters/action01?NAME=martin"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 27
name = [null], of type null
|
参数 [NAME] 与参数 [name] 不是同一个,因此后者缺失。这是与 [ASP.NET Core MVC] 的又一个区别,后者忽略大小写。请注意:
- [@RequestParam] 把动作的参数与 URL 中同名的参数关联起来,包括大小写(如果名称不同,则使用属性 [name] );
- 参数默认是 必需的 ;[required = false] 使它成为可选的,而 [defaultValue] 提供备用值;
- 它的值会被 转换 为声明的类型,转换不可能时会导致 400 错误,并且不执行动作。使用对象类型([Integer],而不是 [int])就可以接收 [null]。
带重音的字符和空格在 URL 中会被编码([%C3%A9] 代表 [é],等等):[Spring MVC] 在绑定之前会对它们解码。浏览器显示编码后的 URL 以及收到的 JSON:

3.2. 示例 08:由类描述的动作模型
当动作有多个参数时,用一个类来描述它们。该类的每个字段都带有 验证约束,以注解的形式表示。这些注解由 [Bean Validation] 定义,它是 [Java] 的验证标准(包 [jakarta.validation]),其使用最广泛的实现是 [Hibernate Validator]。它们不属于 [Spring MVC]:你必须把验证 starter 添加到示例的 [pom.xml] 中:
| <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>course.springmvc</groupId>
<artifactId>examples</artifactId>
<version>1.0</version>
</parent>
<artifactId>example08</artifactId>
<dependencies>
<!-- 验证(Bean Validation、Hibernate Validator) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
</project>
|
- 第 6–10 行:父项目,即 [pom.xml], 位于 [examples] 文件夹中;
- 第 13–19 行:starter [spring-boot-starter-validation] 包含 [Hibernate Validator] 并对其进行配置。请记住,starter 是把其他依赖及其版本和自动配置归并在一起的依赖。示例 09 到 12 共用同一个依赖。
文件 [models/PersonModel.java]:
| package example08.models;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
// 操作的模型:一个每个字段都带有其约束的类
public class PersonModel {
@NotBlank(message = "the name is required")
@Size(min = 2, max = 20, message = "the name must have 2 to 20 characters")
private String name;
@NotNull(message = "the age is required")
@Min(value = 0, message = "the age must be between 0 and 150")
@Max(value = 150, message = "the age must be between 0 and 150")
private Integer age;
@NotNull(message = "the title is required")
@Pattern(regexp = "Mr|Mme|Melle", message = "unknown title")
private String title;
// 可选:没有 @NotNull
@Email(message = "invalid email address")
private String email;
// 访问器(getter 和 setter):模型绑定通过 setter 填充
// 每个字段;JSON 序列化通过 getter 读取它
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
|
我们来说明这段代码:
- 第 3–9 行:验证注解,全部位于 [jakarta.validation.constraints] 包中;
- 第 14–16 行:姓名是必填的且不能为空([@NotBlank] 会拒绝 [null]、空字符串以及仅由空格组成的字符串),并且长度必须在 2 到 20 个字符之间([@Size])。每个注解都接受自定义的错误消息(属性 [message]);
- 第 18–21 行:年龄会被转换为整数,它是必填的([@NotNull]),并且必须在 0 到 150 之间([@Min]、[@Max])。它被声明为 [Integer] 而不是 [int],这样“没有年龄”([null])就会被 [@NotNull] 检测出来,而不是被设为 0;
- 第 23–25 行:称谓必须匹配正则表达式 [Mr|Mme|Melle] ([@Pattern]):它必须是这三个值之一;
- 第 28–29 行:电子邮件地址是可选的(没有 [@NotNull]);如果存在,则必须有效([@Email])。除 [@NotNull] 和 [@NotBlank] 之外的所有约束都接受值 [null]:这正是使字段成为可选的原因;
- 第 33–43 行:访问器。按惯例,字段 [name] 的值由方法 [getName] ([getter])读取,并由方法 [setName]([setter])写入。具有无参构造函数(这里是由 [Java] 隐式提供的构造函数)并且访问器遵循这一惯例的类,称为 JavaBean。这正是数据绑定所期望的形式:[Spring MVC] 使用无参构造函数创建对象,然后对请求中的每个参数,调用同名的 setter:对于 [setName("martin")] ,即 [?name=martin],在把值转换为 setter 的类型之后调用。而 JSON 转换器则通过 getter 读取字段。
文件 [controllers/PersonsController.java]:
| package example08.controllers;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import example08.models.PersonModel;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/persons")
public class PersonsController {
// /persons/action01?name=martin&age=42&title=Mr
// @Valid:在操作运行之前先验证模型;如果模型
// 无效,请求会被自动拒绝(400 错误)
@GetMapping("/action01")
public Map<String, Object> action01(@Valid PersonModel person) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("person", person);
response.put("ageType", person.getAge().getClass().getSimpleName());
return response;
}
}
|
- 第 21 行:动作接收一个 [PersonModel]。该参数没有注解 [@RequestParam]:对于类型不是“简单”类型(字符串、数字、日期等)的参数,[Spring MVC] 隐含使用注解 [@ModelAttribute],也可以显式写出。此时该参数是一个 命令对象 ([command object]),由数据绑定按刚才所述的方式创建并填充。与任何 setter 都不对应的查询参数会被忽略;
- 第 21 行:注解 [@Valid] (来自 [jakarta.validation])要求在对象被填充之后,通过检查其字段上的约束,来 验证该对象。如果数据绑定或验证失败,[Spring MVC] 会抛出 [MethodArgumentNotValidException] 异常:动作不会被执行,响应是 400 错误。这相当于 [[ApiController]] 特性在 [ASP.NET Core MVC] 中的作用;
- 第 22–25 行:动作返回收到的人员及其年龄的类型。[LinkedHashMap] 是一个保持键插入顺序的字典:JSON 将按该顺序输出它们。
示例中的 [application.properties] 文件多了两行:
| # 服务器的监听端口(默认为 8080)
server.port=5000
# Spring Boot 的错误响应不包含调用栈
spring.web.error.include-stacktrace=never
# 错误响应详细列出验证错误
spring.web.error.include-binding-errors=always
|
- 第 6 行:当错误响应由验证检查产生时,它包含错误列表(字段 [errors])。开发工具已经启用了这一点;这一行使它在生产环境中也保持启用。如果没有它——也没有开发工具——错误响应就只剩下 [{"timestamp":"...","status":400,"error":"Bad Request","path":"/persons/action01"}]:客户端知道自己的请求不正确,但不知道原因。
一个有效的请求,带有一个不对应任何字段的 [pirate] 参数:
| curl -i "http://localhost:5000/persons/action01?name=martin&age=42&title=Mr&pirate=1"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 83
{"person":{"age":42,"email":null,"name":"martin","title":"Mr"},"ageType":"Integer"}
|
年龄确实是一个数字(一个 [Integer]),而参数 [pirate] 被忽略了。人员的属性按字母顺序排序:这是 [Jackson] 3([Spring MVC] 使用的 JSON 库)的默认设置。一个无效的查询(为便于阅读,已对响应 JSON 进行格式化:每行一个属性):
| curl -i "http://localhost:5000/persons/action01?name=m&age=abc&title=Dr&email=xx"
|
| HTTP/1.1 400
Content-Type: application/json
{
"timestamp": "2026-09-25T16:46:41.520Z",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='personModel'. Error count: 4",
"errors": [
{
"arguments": [{"arguments":null,"code":"age","codes":["personModel.age","age"],"defaultMessage":"age"}],
"bindingFailure": true,
"code": "typeMismatch",
"codes": ["typeMismatch.personModel.age","typeMismatch.age","typeMismatch.java.lang.Integer","typeMismatch"],
"defaultMessage": "Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'age'; For input string: \"abc\"",
"field": "age",
"objectName": "personModel",
"rejectedValue": "abc"
},
{
"objectName": "personModel",
"field": "email",
"rejectedValue": "xx",
"codes": ["Email.personModel.email","Email.email","Email.java.lang.String","Email"],
"arguments": [{"arguments":null,"code":"email","codes":["personModel.email","email"],"defaultMessage":"email"},[],{"arguments":null,"codes":[".*"],"defaultMessage":".*"}],
"bindingFailure": false,
"code": "Email",
"defaultMessage": "invalid email address"
},
{
"objectName": "personModel",
"field": "title",
"rejectedValue": "Dr",
"codes": ["Pattern.personModel.title","Pattern.title","Pattern.java.lang.String","Pattern"],
"arguments": [{"arguments":null,"code":"title","codes":["personModel.title","title"],"defaultMessage":"title"},[],{"arguments":null,"codes":["Mr|Mme|Melle"],"defaultMessage":"Mr|Mme|Melle"}],
"bindingFailure": false,
"code": "Pattern",
"defaultMessage": "unknown title"
},
{
"objectName": "personModel",
"field": "name",
"rejectedValue": "m",
"codes": ["Size.personModel.name","Size.name","Size.java.lang.String","Size"],
"arguments": [{"arguments":null,"code":"name","codes":["personModel.name","name"],"defaultMessage":"name"},20,2],
"bindingFailure": false,
"code": "Size",
"defaultMessage": "the name must have 2 to 20 characters"
}
],
"path": "/persons/action01"
}
|
动作没有被执行。字段 [errors] 列出了错误,每个被拒绝的字段一条。对于每一条:
- [field]、[rejectedValue]:字段及被拒绝的值;
- [defaultMessage]:错误消息;这是最有用的;
- [code]:被违反的约束的名称([Size]、[Email]等),或者对于转换错误为 [typeMismatch] ;[bindingFailure] 对于转换错误则等于 [true] (错误发生在绑定期间,早于验证);
- [codes]、[arguments]:用于在消息文件中查找消息的键和值。转换错误的英文错误消息(键 [typeMismatch...])就是这样被自定义消息所取代的,如示例 19 所示。
错误的顺序不能保证:它可能在两次运行之间发生变化。不带任何参数时也是如此:
| curl -i http://localhost:5000/persons/action01
|
| HTTP/1.1 400
Content-Type: application/json
{
"timestamp": "2026-09-25T16:46:41.574Z",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='personModel'. Error count: 3",
"errors": [
{
"objectName": "personModel",
"field": "age",
"rejectedValue": null,
"codes": ["NotNull.personModel.age","NotNull.age","NotNull.java.lang.Integer","NotNull"],
"arguments": [{"arguments":null,"code":"age","codes":["personModel.age","age"],"defaultMessage":"age"}],
"bindingFailure": false,
"code": "NotNull",
"defaultMessage": "the age is required"
},
{
"objectName": "personModel",
"field": "title",
"rejectedValue": null,
"codes": ["NotNull.personModel.title","NotNull.title","NotNull.java.lang.String","NotNull"],
"arguments": [{"arguments":null,"code":"title","codes":["personModel.title","title"],"defaultMessage":"title"}],
"bindingFailure": false,
"code": "NotNull",
"defaultMessage": "the title is required"
},
{
"objectName": "personModel",
"field": "name",
"rejectedValue": null,
"codes": ["NotBlank.personModel.name","NotBlank.name","NotBlank.java.lang.String","NotBlank"],
"arguments": [{"arguments":null,"code":"name","codes":["personModel.name","name"],"defaultMessage":"name"}],
"bindingFailure": false,
"code": "NotBlank",
"defaultMessage": "the name is required"
}
],
"path": "/persons/action01"
}
|
每个字段只有一条消息:约束 [@Size] 和 [@Pattern] 接受值 [null];只有 [@NotBlank] 和 [@NotNull] 会拒绝它。与 [@RequestParam] 一样,数据绑定区分大小写:使用 [?NAME=martin&age=42&title=Mr] 时,你会得到“姓名是必填的”这个错误,因为 [NAME] 不匹配任何 setter。
3.2.1. 为什么用 JavaBean 类而不是 record?
从 [Java] 16 开始,单行的 record 描述一个不可修改的数据类:[record Point(int x, int y) {}] 声明了字段 [x] 和 [y]、一个接收所有字段的构造函数,以及读取方法 [x()] 和 [y()]。record 没有 setter。[Spring MVC] 知道如何填充 record:它用查询参数调用其构造函数(这称为 构造函数绑定)。我们不妨把类 [PersonModel] 替换为等价的 record(此时动作使用 [person.age()]读取年龄):
| public record PersonModel(
@NotBlank(message = "the name is required")
@Size(min = 2, max = 20, message = "the name must have 2 to 20 characters")
String name,
@NotNull(message = "the age is required")
@Min(value = 0, message = "the age must be between 0 and 150")
@Max(value = 150, message = "the age must be between 0 and 150")
Integer age,
@NotNull(message = "the title is required")
@Pattern(regexp = "Mr|Mme|Melle", message = "unknown title")
String title,
@Email(message = "invalid email address")
String email) {
}
|
一个有效的查询返回相同的结果,只是 JSON 属性的顺序不同:record 的属性按其组件的顺序写出([{"name":"martin","age":42,"title":"Mr","email":null}])。但前面那个无效的查询现在只返回一个错误:
| curl -i "http://localhost:5000/persons/action01?name=m&age=abc&title=Dr&email=xx"
|
| HTTP/1.1 400
Content-Type: application/json
{
"timestamp": "2026-09-25T16:47:45.491Z",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='personModel'. Error count: 1",
"errors": [
{
"arguments": [{"arguments":null,"code":"age","codes":["personModel.age","age"],"defaultMessage":"age"}],
"bindingFailure": true,
"code": "typeMismatch",
"codes": ["typeMismatch.personModel.age","typeMismatch.age","typeMismatch.java.lang.Integer","typeMismatch"],
"defaultMessage": "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; For input string: \"abc\"",
"field": "age",
"objectName": "personModel",
"rejectedValue": "abc"
}
],
"path": "/persons/action01"
}
|
年龄转换失败;因此,由于其中一个参数没有值,record 的构造函数无法被调用;没有对象,就没有验证:姓名、称谓和电子邮件地址中的错误都不会被报告。而对于 JavaBean,每个 setter 是独立调用的:转换不正确的字段保持为空并得到一个转换错误,而其他字段会被填充,验证照常进行(示例 09)。对于 HTML 表单来说,目标是一次性报告 所有 错误,这一点至关重要:因此本课程中的所有表单都是 JavaBean 表单。对于字段不可能出现转换错误的模型,record 仍然适用:示例 10 就是这种情况。
这种自动拒绝适用于 JSON 服务器,它由以自己的方式显示错误的 [JavaScript] 客户端来查询。对于 HTML 应用程序,JSON 错误毫无意义:目标是连同错误一起重新显示表单。下面的示例展示如何保持控制权。
3.3. 示例 09:由动作执行的验证
示例 09 中的 [PersonModel] 类与示例 08 中的相同;只有控制器变了。[controllers/PersonsController.java] 文件:
| package example09.controllers;
import java.util.stream.Collectors;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import example09.models.PersonModel;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/persons")
public class PersonsController {
// 紧跟在模型之后的 BindingResult 参数:操作总是会
// 被执行,由操作决定如何处理无效的模型
@GetMapping(value = "/action01", produces = MediaType.TEXT_HTML_VALUE)
public String action01(@Valid PersonModel person, BindingResult result) {
// result:模型的绑定和验证的结果
if (!result.hasErrors()) {
return "<p>Welcome %s %s (%d years old)</p>".formatted(person.getTitle(), person.getName(), person.getAge());
}
// 错误,逐字段列出
String items = result.getFieldErrors().stream()
.map(error -> "<li>%s: %s</li>".formatted(error.getField(), error.getDefaultMessage()))
.collect(Collectors.joining());
return "<p>The form contains errors:</p><ul>" + items + "</ul>";
}
}
|
我们来剖析这段代码:
- 第 20 行:[produces] 属性(属于 [@GetMapping] )设定响应类型:[MediaType.TEXT_HTML_VALUE] 是常量 ["text/html"]。因此,动作返回的字符串会作为 HTML 页面发送;
- 第 21 行:动作有第二个参数,类型为 [BindingResult],放在 紧接着 被验证的模型之后。它的出现改变了一切:发生绑定或验证错误时,[Spring MVC] 不再抛出异常;它把错误存放在这个 [BindingResult] 中,并且 执行动作,由动作决定如何处理这些错误。[BindingResult] 所起的作用与 [ModelState] 在 [ASP.NET Core MVC] 中相同;
- 第 23–25 行:[hasErrors()] 表示是否存在错误。如果没有错误,则返回欢迎页面([%d] 被替换为一个整数);
- 第 27–29 行:否则,返回错误列表。[getFieldErrors()] 返回与字段相关联的错误列表([FieldError]),以及字段名([getField()])和消息([getDefaultMessage()])。处理过程使用来自 [Java] 流 ([Stream])的 API:[stream()] 逐个生成列表项,[map] 转换每一项(这里是把一个错误转换成一行:HTML 的 [<li>]),[collect(Collectors.joining())] 把所有内容拼接成一个字符串。[map] 的参数是一个 lambda:一个匿名函数,写作 [parameter -> expression];
- 第 30 行:列出错误的页面。两种情况下,响应的状态码都是 200。
浏览器中的一个有效请求:

一个无效请求:

转换错误会作为验证错误出现在 [BindingResult] 中,但不会妨碍对其他字段的验证:
| curl -i "http://localhost:5000/persons/action01?name=m&age=abc&title=Mr"
|
| HTTP/1.1 200
Content-Type: text/html;charset=UTF-8
Content-Length: 247
<p>The form contains errors:</p><ul><li>age: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'age'; For input string: "abc"</li><li>name: the name must have 2 to 20 characters</li></ul>
|
这就是案例研究中所有表单都将使用的技术(见示例 19):动作接收表单(一个用 [@Valid] 标注的 JavaBean),后面跟着一个 [BindingResult],如果有错误就重新显示表单。
3.4. 示例 10:多值参数
同一个参数可以在请求中多次出现:表单上的复选框或多选列表就是这种情况([?color=red&color=green])。
[controllers/ArraysController.java] 文件:
| package example10.controllers;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import example10.models.ChoiceModel;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/arrays")
public class ArraysController {
// /arrays/action01?color=red&color=green:一个简单参数
@GetMapping("/action01")
public Map<String, String> action01(@RequestParam(required = false) String color) {
Map<String, String> response = new LinkedHashMap<>();
response.put("color", color);
return response;
}
// /arrays/action02?color=red&color=green:一个列表
@GetMapping("/action02")
public Map<String, Object> action02(@RequestParam(required = false) List<String> color) {
List<String> colors = color == null ? List.of() : color;
Map<String, Object> response = new LinkedHashMap<>();
response.put("color", colors);
response.put("count", colors.size());
return response;
}
// /arrays/action03?color=red:一个列表,由 ChoiceModel 验证
@GetMapping("/action03")
public Map<String, Object> action03(@Valid ChoiceModel choice, BindingResult result) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("colors", choice.color());
response.put("valid", !result.hasErrors());
response.put("errors", result.getAllErrors().stream().map(ObjectError::getDefaultMessage).toList());
return response;
}
}
|
[action01] 动作(第 22–27 行)展示了单个参数会收到什么:
| curl -i "http://localhost:5000/arrays/action01?color=red"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
{"color":"red"}
|
| curl -i "http://localhost:5000/arrays/action01?color=red&color=green"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 21
{"color":"red,green"}
|
类型为 [String] 的参数在收到多个值时,会把它们 连接起来,以逗号分隔:["red,green"]。这是一个陷阱:你以为只收到一种颜色,实际上收到的是一个伪装起来的颜色列表。列表类型的参数([action02],第 30–37 行)会把它们全部接收,每个值是列表中的一个元素。[List<String>] 是字符串列表;[List.of()] (第 32 行)是一个空列表,在参数缺失时用它代替 [null] :
| curl -i "http://localhost:5000/arrays/action02?color=red"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 27
{"color":["red"],"count":1}
|
| curl -i "http://localhost:5000/arrays/action02?color=red&color=green"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 35
{"color":["red","green"],"count":2}
|
| curl -i "http://localhost:5000/arrays/action02"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 22
{"color":[],"count":0}
|
反过来,包含逗号的单个值会被拆分:
| curl -i "http://localhost:5000/arrays/action02?color=red,green"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 35
{"color":["red","green"],"count":2}
|
把字符串转换为列表,与把列表转换为字符串一样,都使用逗号作为分隔符。我们也可以声明一个数组([String[] color])。剩下的就是验证这个列表。文件 [models/ChoiceModel.java]:
| package example10.models;
import java.util.List;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
// 一个列表,并对列表的每个元素施加约束:
// @Pattern 注解放在泛型类型 List<...> 的内部
public record ChoiceModel(
@Size(min = 1, message = "choose at least one color")
List<@Pattern(regexp = "red|green|blue", message = "unknown color: ${validatedValue}") String> color) {
// record 的“紧凑”构造函数:缺失的列表变为空列表
public ChoiceModel {
color = color == null ? List.of() : color;
}
}
|
我们来说明这段代码:
- 第 10 行:[ChoiceModel] 是一个只有一个字段的 record (见示例 03 和 08),该字段为 [color]。构造函数绑定在这里没有问题:字符串列表不会产生转换错误;
- 第 12 行:[@Size(min = 1)] 应用于列表时,指的是列表中的元素个数:至少要有一个;
- 第 13 行:注解 [@Pattern] 放在泛型类型 之内、[String] 之前:它不是应用于列表,而是应用于 列表的每个元素。每种颜色必须是 [red]、[green] 或 [blue]。在消息中,[${validatedValue}] 会被替换为被拒绝的值;
- 第 16–18 行:record 的 紧凑构造函数 :在构造函数开头、字段赋值之前执行的一个代码块,它可以修改构造函数的参数。这里,缺失的列表([null])会变成空列表。
[action03] 动作属于 [ArraysController] 控制器,它接收一个经过验证的 [ChoiceModel],后面跟着一个 [BindingResult],并返回其内容以及验证状态。[choice.color()] 读取 record 的字段。[result.getAllErrors()] 返回所有错误,而 [ObjectError::getDefaultMessage] 是一个 方法引用:lambda [error -> error.getDefaultMessage()] 的简写。[toList()] 把流收集成一个列表。
| curl -i "http://localhost:5000/arrays/action03?color=red&color=green"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 51
{"colors":["red","green"],"valid":true,"errors":[]}
|
| curl -i "http://localhost:5000/arrays/action03?color=red&color=black"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 74
{"colors":["red","black"],"valid":false,"errors":["unknown color: black"]}
|
| curl -i "http://localhost:5000/arrays/action03"
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 66
{"colors":[],"valid":false,"errors":["choose at least one color"]}
|
[ASP.NET Core MVC] 需要用 [C#] 编写一个验证方法来检查列表中的每一项;而使用 [Bean Validation] 时,在泛型类型中加一个注解就足够了。
3.5. 示例 11:POST 请求的参数
通过 POST 方法提交的 HTML 表单把它的字段放在请求 体中,而不是 URL 中。[controllers/PostController.java] 文件:
| package example11.controllers;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import example11.models.PersonModel;
import jakarta.validation.Valid;
import tools.jackson.databind.JsonNode;
@RestController
@RequestMapping("/post")
public class PostController {
// HTML 表单的字段(application/x-www-form-urlencoded 正文)
@PostMapping("/action01")
public Map<String, Object> action01(@RequestHeader("Content-Type") String type,
@RequestParam MultiValueMap<String, String> fields) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("receivedType", type);
response.put("fields", fields);
return response;
}
// JSON 正文:由 @RequestBody 反序列化
@PostMapping("/action02")
public Map<String, Object> action02(@RequestHeader("Content-Type") String type, @RequestBody JsonNode body) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("receivedType", type);
response.put("body", body);
return response;
}
// 表单的单个字段:@RequestParam,与 URL 参数一样
@PostMapping("/action03")
public String action03(@RequestParam(required = false) String name) {
return "name = [%s]".formatted(name);
}
// 表单字段,由 PersonModel 类绑定并验证
@PostMapping("/action04")
public Map<String, Object> action04(@Valid PersonModel person, BindingResult result) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("person", person);
response.put("valid", !result.hasErrors());
response.put("errors", result.getAllErrors().stream().map(ObjectError::getDefaultMessage).sorted().toList());
return response;
}
}
|
我们来说明这段代码:
- 第 25 行:[@PostMapping] 把动作与 POST 请求关联起来,就像 [@GetMapping] 对 GET 请求所做的那样;
- 第 26 行:[@RequestHeader("Content-Type")] 提供请求头的值:这里是请求体的类型;
- 第 27 行:一个类型为 [MultiValueMap<String, String>], 并标注为 [@RequestParam], 的参数,接收所有请求参数。[MultiValueMap] 是一个字典,其中每个键关联一个值的 列表 :它会保留重复参数的所有值,而示例 07 中的 [Map<String, String>] 只会保留一个;
- 第 36 行:[@RequestBody] 指示系统读取请求体并 反序列化它——也就是把它转换为一个 [Java] 对象。请求体必须是 JSON 文档(这正是 [JavaScript] 客户端发送的内容),由 [Jackson] 库读取。[JsonNode] 表示任意 JSON 文档;我们也可以声明一个类或一个 record。第 18 行:在 [Jackson] 3(由 [Spring Boot] 4 使用)中,这些类位于 [tools.jackson.databind] 包中(不再像 [com.fasterxml.jackson.databind] 在 [Jackson] 2 中那样);
- 第 44–45 行:[@RequestParam] 读取表单字段的方式与读取 URL 参数完全相同;
- 第 50–51 行:整个表单,由 [PersonModel] 类(示例 08 中该类在 [example11.models] 包中的副本)进行绑定和验证(一个命令对象,如示例 09 所示);
- 第 55 行:[sorted()] 对消息排序,使错误的顺序在每次执行之间保持一致。
[-d] 选项(属于 [curl] )发送一个 POST 请求,请求体采用 HTML 表单的格式([application/x-www-form-urlencoded]):
| curl -i -d "name=martin&age=42" http://localhost:5000/post/action01
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 94
{"receivedType":"application/x-www-form-urlencoded","fields":{"name":["martin"],"age":["42"]}}
|
每个字段关联一个值列表,在这里该列表只包含一个值。相同的内容用 JSON 格式表示:
| curl -i -H "Content-Type: application/json" -d '{"name":"martin","age":42}' http://localhost:5000/post/action02
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 69
{"receivedType":"application/json","body":{"name":"martin","age":42}}
|
([-H] 选项(属于 [curl] )向请求添加一个头;在 [Windows] 的命令提示符下,你应输入 [-d "{\"name\":\"martin\",\"age\":42}"])。在第一种情况下,年龄是一个字符串(HTML 表单只携带文本),而在第二种情况下它是一个数字。[Spring MVC] 根据请求中的 [Content-Type] 头选择读取请求体的转换器。因此,期望 JSON 的 [@RequestBody] 动作会拒绝其他类型的请求体,并返回 415 错误([Unsupported Media Type],即不支持的内容类型):
| curl -i -d "name=martin&age=42" http://localhost:5000/post/action02
|
| HTTP/1.1 415
Accept: application/json, application/*+json
Content-Type: application/json
{"timestamp":"2026-09-25T16:48:45.851Z","status":415,"error":"Unsupported Media Type","message":"Content-Type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported.","path":"/post/action02"}
|
响应头 [Accept] 列出了所接受的类型。而无效的 JSON 请求体则会导致 400 错误:
| curl -i -H "Content-Type: application/json" -d '{"name":"martin",' http://localhost:5000/post/action02
|
| HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-09-25T16:48:45.879Z","status":400,"error":"Bad Request","message":"JSON parse error: Unexpected end-of-input within/between Object entries","path":"/post/action02"}
|
另外两个动作:
| curl -i -d "name=martin&age=42" http://localhost:5000/post/action03
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 15
name = [martin]
|
| curl -i -d "name=martin&age=42&title=Mme" http://localhost:5000/post/action04
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 89
{"person":{"age":42,"email":null,"name":"martin","title":"Mme"},"valid":true,"errors":[]}
|
| curl -i -d "name=martin&age=200" http://localhost:5000/post/action04
|
| HTTP/1.1 200
Content-Type: application/json
Content-Length: 149
{"person":{"age":200,"email":null,"name":"martin","title":null},"valid":false,"errors":["the age must be between 0 and 150","the title is required"]}
|
[@RequestParam] 和命令对象不区分 URL 和请求体:它们把 URL 的参数和表单字段 视为一个整体。因此,在两处都出现的参数会收到两个值:
| curl -i "http://localhost:5000/post/action03?name=durand" -d "name=martin"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 22
name = [durand,martin]
|
POST 动作与 GET 动作一样,响应的状态码也是 200。对于 HTML 应用程序,POST 动作要么用一个页面(重新显示的表单)响应,要么用重定向响应(见示例 20)。
3.6. 示例 12:自定义数据绑定与验证
数据绑定和验证是可以扩展的。案例研究只适度地用到了它们,但理解它们有助于弄清 [Spring MVC] 的工作原理。
| 12-custom-binding/
├── src/main/java/example12/
│ ├── controllers/
│ │ └── ExamplesController.java
│ ├── binding/
│ │ ├── DateFrConverter.java
│ │ ├── Language.java
│ │ ├── LanguageResolver.java
│ │ ├── NoSpace.java
│ │ ├── NoSpaceValidator.java
│ │ └── WebConfig.java
│ └── Example12Application.java
├── src/main/resources/
│ └── application.properties
└── pom.xml
|
3.6.1. 转换器:DateFrConverter
要把字符串 ["42"] 转换为 [int],[Spring MVC] 使用 转换器 ([Converter])。它为所有常见类型提供了转换器;你也可以编写自己的转换器。文件 [binding/DateFrConverter.java]:
| package example12.binding;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import org.springframework.core.convert.converter.Converter;
// 一个转换器:将法式日期 "23/09/2026" 转换为 LocalDate。
// 它将用于任何 LocalDate 类型的参数(参见 WebConfig)
public class DateFrConverter implements Converter<String, LocalDate> {
// uuuu:年份;STRICT:"31/02/2026" 会被拒绝(而不是被调整为 2 月 28 日)
private static final DateTimeFormatter FORMAT =
DateTimeFormatter.ofPattern("dd/MM/uuuu").withResolverStyle(ResolverStyle.STRICT);
@Override
public LocalDate convert(String text) {
try {
return LocalDate.parse(text, FORMAT);
} catch (DateTimeParseException e) {
// 失败:抛出异常,Spring 会将其转换为转换错误
throw new IllegalArgumentException("[" + text + "] is not a valid dd/mm/yyyy date");
}
}
}
|
- 第 12 行:转换器实现泛型接口 [Converter<S, T>],其中 [S] 是源类型,[T] 是 目标类型:这里是从 [String] 到 [LocalDate] (不含时间的日期);
- 第 15–16 行:日期格式 [dd/mm/yyyy]。在 [STRICT] 模式下,不存在的日期(31/02/2026)会被拒绝;该模式要求把年份写成 [uuuu] 而不是 [yyyy];
- 第 19–21 行:该接口唯一的方法 [convert] 返回转换得到的日期;
- 第 22–25 行:如果转换失败,转换器会抛出异常。[Spring MVC] 随即产生转换错误,就像 [?age=abc] 那样:对于 [@RequestParam] 是 400 错误,对于命令对象的字段,则是 [typeMismatch] 错误出现在 [BindingResult] 中。我们抛出的异常被保留为转换错误的 原因 :我们将在控制器中取出它的消息。
3.6.2. 参数解析器:@Language 注解与 LanguageResolver
动作的参数可以来自 URL 或表单之外的来源。对于动作的每个参数,[Spring MVC] 会查询一组称为 [argument resolvers] (“参数解析器”)的对象:第一个声明自己能处理该参数的解析器会提供它的值。[@RequestParam]、[@RequestHeader]、[@RequestBody] 等等就是这样工作的。你可以添加自己的解析器。首先,你需要一种方式来标识相关的参数:一个“自定义”注解。文件 [binding/Language.java]:
| package example12.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 一个“自制”注解:@Language String language。它本身
// 什么也不做:它只是标记一个参数,LanguageResolver 知道如何填充该参数。
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Language {
}
|
- 第 12 行:[@interface] 声明一个注解。该注解没有属性;
- 第 10 行:[@Target] 指定注解可以放置的位置:这里只能放在方法参数上;
- 第 11 行:[@Retention(RetentionPolicy.RUNTIME)]:该注解保留在编译后的代码中,并且在运行时可读。这对于 [Spring MVC] 识别它至关重要。
文件 [binding/LanguageResolver.java]:
| package example12.binding;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
// 一个“参数解析器”:它为带有 @Language 注解的参数提供值,
// 该值读取自头 "Accept-Language: fr-FR,fr;q=0.9,en;q=0.8" -> "fr"
public class LanguageResolver implements HandlerMethodArgumentResolver {
// 这个解析器是否处理该参数?
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(Language.class) && parameter.getParameterType() == String.class;
}
// 参数的值
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest request, WebDataBinderFactory binderFactory) {
String header = request.getHeader("Accept-Language");
String first = header == null ? "" : header.split(",")[0].trim();
return first.length() >= 2 ? first.substring(0, 2).toLowerCase() : "fr";
}
}
|
- 第 11 行:解析器实现 [HandlerMethodArgumentResolver] 接口;
- 第 14–17 行:对于它处理的参数,[supportsParameter] 返回 [true] :这些参数带有注解 [@Language] 且类型为 [String]。[MethodParameter] 描述动作的一个参数;
- 第 20–26 行:[resolveArgument] 提供参数的值。在它的参数中,[NativeWebRequest] 提供对请求的访问。第 23 行:头 [Accept-Language],它指定用户偏好的语言。第 24–25 行:第一种语言的前两个字母(小写),如果缺少该头,则为 ["fr"] 。运算符 [? :] 在条件为真时返回第二个操作数,否则返回第三个操作数。
3.6.3. 验证约束:@NoSpace
自定义验证约束由两个元素组成:一个注解和执行验证的类。文件 [binding/NoSpace.java]:
| package example12.binding;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
// 一个“自制”的验证约束:@NoSpace。
// @Constraint 指定执行检查的类。
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NoSpaceValidator.class)
public @interface NoSpace {
// 默认的错误消息
String message() default "the field must not contain any space";
// Bean Validation 标准要求的两个属性(很少使用)
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
- 第 13 行:该约束可以应用于类的字段或方法的参数;
- 第 15 行:[@Constraint] 把该注解变成一个 [Bean Validation] 约束,并指定验证它的类;
- 第 19 行:默认的错误消息。注解的属性被声明为一个没有参数的方法,而 [default] 为它赋予默认值:我们可以写 [@NoSpace] 或 [@NoSpace(message = "...")];
- 第 22–24 行:标准要求的两个属性:[groups] 允许你只检查约束的一个子集,而 [payload] 允许你给约束附加信息。我们不使用它们,但必须声明。
文件 [binding/NoSpaceValidator.java]:
| package example12.binding;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
// 针对 String 类型的值,检查 @NoSpace 约束
public class NoSpaceValidator implements ConstraintValidator<NoSpace, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// 接受 null:要求非空是 @NotNull 的职责
return value == null || !value.contains(" ");
}
}
|
- 第 7 行:验证类实现 [ConstraintValidator<A, T>],其中 [A] 是注解,[T] 是 被验证值的类型;
- 第 10–13 行:如果值可以接受,[isValid] 返回 [true] 。值 [null] 是被接受的,因为除 [@NotNull] 和 [@NotBlank] 之外,所有标准约束都满足这一点。
3.6.4. 配置:WebConfig
转换器和解析器必须在 [Spring MVC] 中声明;约束则通过注解 [@Constraint] 来识别。文件 [binding/WebConfig.java]:
| package example12.binding;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
// WebMvcConfigurer:对 Spring MVC 的配置进行补充的配置类。
// 我们重写自己感兴趣的方法。
@Configuration
public class WebConfig implements WebMvcConfigurer {
// 转换器:String -> LocalDate
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateFrConverter());
}
// “参数解析器”:@Language 参数
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new LanguageResolver());
}
}
|
- 第 12 行:[@Configuration] 表示 这是一个 配置类:[Spring Boot] 在启动时发现它(它位于包含 [Example12Application] 类的包的子包中),创建它的实例并使用它;
- 第 13 行:[WebMvcConfigurer] 接口允许你 扩展 [Spring MVC] 的配置,该配置由 [Spring Boot] 建立,而不替换它。它有许多方法,默认什么都不做;我们重写([@Override])我们感兴趣的那些;
- 第 16–19 行:[addFormatters] 注册转换器。[DateFrConverter] 将用于应用程序中 任何 类型为 [LocalDate] 的参数;
- 第 22–25 行:[addArgumentResolvers] 把解析器添加到 [Spring MVC] 的解析器列表中。
3.6.5. 控制器
[controllers/ExamplesController.java] 文件:
| package example12.controllers;
import java.time.LocalDate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import example12.binding.Language;
import example12.binding.NoSpace;
@RestController
@RequestMapping("/examples")
public class ExamplesController {
// /examples/schedule?day=23/09/2026:自定义转换器(DateFrConverter)
@GetMapping("/schedule")
public String schedule(@RequestParam LocalDate day) {
return "schedule for the day [" + day + "]";
}
// /examples/hello:一个并非来自 URL、而是来自头的参数
@GetMapping("/hello")
public String hello(@Language String language) {
return "en".equals(language) ? "Hello!" : "Bonjour !";
}
// /examples/search?keyword=spring:一个自定义的验证约束,
// 直接放在操作的参数上
@GetMapping("/search")
public String search(@RequestParam(required = false) @NoSpace String keyword) {
return "search for [" + keyword + "]";
}
// —————————————— 错误
// @ExceptionHandler:控制器的一个方法,它将其某个操作(或其参数绑定)抛出的异常
// 转换为响应
// 无法转换(DateFrConverter 抛出了异常)
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String conversion(MethodArgumentTypeMismatchException e) {
// 原始异常,即来自 DateFrConverter 的那个:其消息是我们自己的
return e.getMostSpecificCause().getMessage();
}
// 违反验证约束(@NoSpace)的参数
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String validation(HandlerMethodValidationException e) {
return e.getAllErrors().get(0).getDefaultMessage();
}
}
|
- 第 24 行:一个类型为 [LocalDate] 的普通参数:没有任何迹象表明应使用 [DateFrConverter];是它的类型指明了这一点;
- 第 30 行:参数 [language] 由 [LanguageResolver] 通过注解 [@Language] 提供;
- 第 37 行:验证约束也可以直接应用于动作的参数(这里与 [@RequestParam] 一起使用)。无需 [@Valid]:[Spring MVC] 会自动验证带有约束的参数。如果验证失败,它会抛出 [HandlerMethodValidationException] 异常;
- 第 46–51 行:带有 [@ExceptionHandler] 注解的方法是一个 异常处理器:如果控制器的某个动作或其参数的绑定抛出了与该方法参数类型相同的异常(这里是 [MethodArgumentTypeMismatchException],即转换失败),[Spring MVC] 就会调用它,而不是生成自己的错误响应。它返回的内容成为响应,状态码由 [@ResponseStatus] 设定:400([HttpStatus.BAD_REQUEST])。第 50 行:[getMostSpecificCause()] 返回原始异常——由 [DateFrConverter] 抛出的那个——它包含我们的消息;
- 第 54–58 行:参数验证失败的情况也是如此。[getAllErrors()] 返回错误列表,我们从中保留第一条错误的消息。
如果没有这两个处理器,响应将是来自 [Spring Boot] 的 JSON 错误,其中针对日期的技术性消息是英文的,不包含我们自己的消息。异常处理器只作用于它所在的控制器;在示例 24 中,我们将看到如何为整个应用程序编写一个([@ControllerAdvice])。
结果如下:
| curl -i "http://localhost:5000/examples/schedule?day=23/09/2026"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 33
schedule for the day [2026-09-23]
|
| curl -i "http://localhost:5000/examples/schedule?day=2026-09-23"
|
| HTTP/1.1 400
Content-Type: text/plain;charset=UTF-8
Content-Length: 43
[2026-09-23] is not a valid dd/mm/yyyy date
|
| curl -i "http://localhost:5000/examples/schedule?day=31/02/2026"
|
| HTTP/1.1 400
Content-Type: text/plain;charset=UTF-8
Content-Length: 43
[31/02/2026] is not a valid dd/mm/yyyy date
|
日期 [LocalDate] 在转换为字符串时写作 [2026-09-23] (ISO 格式)。语言:
| curl -i -H "Accept-Language: fr-FR,fr;q=0.9" http://localhost:5000/examples/hello
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 9
Bonjour !
|
| curl -i -H "Accept-Language: en-US,en;q=0.9" http://localhost:5000/examples/hello
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 6
Hello!
|
约束 [@NoSpace]:
| curl -i "http://localhost:5000/examples/search?keyword=spring"
|
| HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 19
search for [spring]
|
| curl -i "http://localhost:5000/examples/search?keyword=spring%20mvc"
|
| HTTP/1.1 400
Content-Type: text/plain;charset=UTF-8
Content-Length: 36
the field must not contain any space
|
([%20] 是空格在 URL 中的编码)
3.6.6. 结论
动作模型是通过绑定请求中的数据构建的:URL 的参数和表单字段([@RequestParam]、命令对象)、JSON 请求体([@RequestBody])、头([@RequestHeader]),以及自定义解析器能够提供的任何内容。这些值会被转换为参数的类型,然后当模型带有 [Bean Validation] 约束并标注了 [@Valid] 时,依据这些约束进行验证。涉及 [@RequestParam] 的转换错误,或者没有 [BindingResult] 的无效模型,会导致 400 错误且不执行动作:这对 JSON 服务器是合适的。对于 HTML 应用程序,表单是一个标注了 [@Valid] 的 JavaBean,后面跟着动作要查询的 [BindingResult] 参数(示例 09),以便能够连同错误一起重新显示表单。这是下一章的主题。