java - 执行 POST 请求并读取用户使用 Spring Boot Rest api 输入的 POST 数据时的 JSON 模式验证
问题描述
如何在使用指定模式的POST 请求期间验证(使用指定模式)用户输入的 JSON(我们必须在每次通过 POST 请求接收到 JSON 数据时验证它)?另外,如何从发布请求中实际提取用户输入的数据?我做了以下提取数据输入我的用户:
@PostMapping("/all-configs")
public Animal createConfig( @RequestBody Animal ani) {
try {
System.out.println(ani);//output: net.company.sprinboot.model.Animal@110e19d9
System.out.println(ani.toString());//output: net.company.sprinboot.model.Animal@110e19d9
String str = ani.toString();
System.out.println(str);//output: net.company.sprinboot.model.Animal@110e19d9
} … … …. .. . ...etc
请帮忙!我如何才能真正读取用户在发布请求中输入的 JSON 数据?
解决方案
如何在 POST 请求期间使用指定的模式验证用户输入的 JSON(我们必须在每次通过 POST 请求接收到 JSON 数据时验证它)?
添加注释@Valid
(来自javax.validation.valid
),如下所示:
public Animal createConfig(@Valid @RequestBody Animal ani) {
在 Animal DTO上,在要验证的字段上添加注释,例如:
public class Animal implements Serializable {
...
@Size(max = 10)
@NotBlank
private String name;
...
}
当 Spring Boot 找到一个带有 @Valid 注释的参数时,它会引导 Hibernate Validator(JSR 380 实现)并要求它执行 bean 验证。
当验证失败时,Spring Boot 会抛出一个MethodArgumentNotValidException
.
另外,如何从发布请求中实际提取用户输入的数据?
在 Animal POJO 上使用 getter 方法。例子:
String name = ani.getName();
更新:
另外,如果我有一个像这样的 json:{"hype": {"key1":"value1"} }... 那么我如何访问 hype.key1 中的 value1?
@RestController
public class Main {
@PostMapping("/all-configs")
public void createConfig(@Valid @RequestBody Animal ani) {
Map<String, String> hype = ani.getHype();
System.out.println(hype.get("key1"));
}
}
public class Animal implements Serializable {
private Map<String, String> hype;
public Map<String, String> getHype() {
return hype;
}
public void setHype(Map<String, String> hype) {
this.hype = hype;
}
}
输出:
价值1
推荐阅读
- php - 无法在 Cakephp shell 中加载数据库配置
- python-3.x - 在python中使用“for循环”查找数字的素数
- c - 如何使函数体在c中重复
- angularjs - Angular JS - 列表中的单个内容切换器
- python - Python:在列表中添加正值
- java - 空对象引用错误上的 setOnClickListener()
- vcf-vcard - 如何检测 vCard 中的更改?
- registration - 在 Keycloak 中有一种方法可以限制特定电子邮件域的注册
- javascript - jquery中的动态添加类
- php - 如何使用 eloquent 获得行位置