java - 即使在最简单的项目中,Spring Boot 路径变量验证也不起作用
问题描述
有点奇怪。我什至正在实现最简单的项目,其中路径变量验证和验证不起作用。
我有那个休息控制器:
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.Min;
@RestController
@Validated
@RequestMapping("/")
public class MyController {
@GetMapping("/student/{age}")
ResponseEntity<String> student(@PathVariable("age") @Valid @Min(5) int age) {
return ResponseEntity.ok("Your age is " + age);
}
}
我的 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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
并始终返回您的年龄是 age ,无论我输入什么作为年龄,所以 @Min 验证不起作用。
我还上传了 pom.xml,也许这会有用。
这段代码有什么问题?
解决方案
是的,我做到了。
我需要从以下位置更改依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
至
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
然后在 application.properties 添加这些行:
server.error.include-message=always
server.error.include-binding-errors=always
感谢所有试图提供帮助的人!
推荐阅读
- ios - UNITY 2019.3.3 WebGL(wasm)在IOS上的可执行内存不足
- excel - 我正在尝试制作可切换选项卡,但在编译 vba 期间出现错误
- reactjs - 如何在本机反应中显示文本框以在文本框中显示 HTML 内容,如文本?
- python - 为什么这不对列表进行排序?
- angular - 不带复选框但列表元素突出显示的材料选择列表 - 查找示例
- reactjs - 反应更新状态显示其他组件
- ios - FScalendar 自定义
- c# - 当我使用 ToListAsync 方法时线程不起作用
- javascript - 使用 styled props 将动态 css 属性应用于 div
- react-native - 如何显示包含多个数组的对象的数据?