AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79412128
Accepted
PatPanda
PatPanda
Asked: 2025-02-04 22:58:05 +0800 CST2025-02-04 22:58:05 +0800 CST 2025-02-04 22:58:05 +0800 CST

SpringBoot @Valid 在一个字段上,基于另一个字段的值

  • 772

我想使用 SpringBoot @Valid 来验证 http 请求字段,但基于同一个 http 请求的另一个字段。

我有以下代码:

<?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 http://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>3.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <artifactId>question</artifactId>

    <properties>
        <maven.compiler.source>23</maven.compiler.source>
        <maven.compiler.target>23</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
class FieldValidationApplication {

    public static void main(String[] args) {
        SpringApplication.run(FieldValidationApplication.class, args);
    }

}
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class FieldValidationController {

    @PostMapping("/validate")
    String question(@Valid @RequestBody SomeRequest someRequest) {
        return "please validate the field";
    }

}

record SomeRequest(int score,
                   String fieldPositive,
                   String fieldZeroAndNegative
                   ) 
{ }

验证规则非常简单:

请求负载包含字段 score。如果字段 score 的值严格为正数,则我需要检查字段 fieldPositive 是否为有效字符串,以及 fieldZeroAndNegative 是否为 null。

例如:

{
  "score": 1,
  "fieldPositive": "thisisok"
}

但那些不是:

{
  "score": 1
}

{
  "score": 1,
  "fieldPositive": ""
}

{
  "score": 1,
  "fieldPositive": "below fieldZeroAndNegative should be null",
  "fieldZeroAndNegative": "not ok"
}

其他字段的规则类似(代码就在下面)。

这是我尝试过的,我创建了自定义注释:

record SomeRequest(int score,
                   @ValidateThisFieldOnlyIfScoreIsPositive String fieldPositive,
                   @ValidateThisFieldOnlyIfScoreIsZeroOrNegative String fieldZeroAndNegative
                   ) 
{ }

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = ValidateThisFieldOnlyIfScoreIsPositiveValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidateThisFieldOnlyIfScoreIsPositive
{
    String message() default "Field is invalid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}


import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

class ValidateThisFieldOnlyIfScoreIsPositiveValidator implements ConstraintValidator<ValidateThisFieldOnlyIfScoreIsPositive, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        System.out.println("hello, the value of the field fieldPositive is " + value);
        System.out.println("However, I cannot get the value of the field score");
        if (" SomeRequest score " > 0) { //how to get the value of the field score here?
            return value != null && !value.isEmpty() && value.length() > 3;
        }
        if (" SomeRequest score"  <= 0) {
            return value == null;
        }
        ...
    }

}

import jakarta.validation.Constraint;
import jakarta.validation.Payload;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = ValidateThisFieldOnlyIfScoreIsZeroOrNegativeValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidateThisFieldOnlyIfScoreIsZeroOrNegative
{
    String message() default "Field is invalid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

class ValidateThisFieldOnlyIfScoreIsZeroOrNegativeValidator implements ConstraintValidator<ValidateThisFieldOnlyIfScoreIsZeroOrNegative, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        System.out.println("hello, the value of the field fieldZeroAndNegative is " + value);
        System.out.println("However, I cannot get the value of the field score");
        if (" SomeRequest score " <= 0) { //how to get the value of the field score here?
            return value != null && !value.isEmpty() && value.length() > 3;
        }
        if (" SomeRequest score" > 0) {
            return value == null;
        }

    }

}

我不确定每个字段使用一个注释是否是可行的方法。

问题:

如何在验证器中获取同一请求的两个字段(或多个字段)?

java
  • 1 1 个回答
  • 49 Views

1 个回答

  • Voted
  1. Best Answer
    Jerre
    2025-02-04T23:18:32+08:002025-02-04T23:18:32+08:00

    要根据同一请求对象中另一个字段的值来验证一个字段,您需要在类级别而不是字段级别应用验证。这样,验证器就可以访问对象的所有字段。

    解决方案:使用类级约束

    1. 创建自定义验证注释

    创建可应用于整个类的自定义注释:

    import jakarta.validation.Payload;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Constraint(validatedBy = SomeRequestValidator.class)
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ValidSomeRequest {
        String message() default "Invalid request data";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    
    1. 实现验证器

    创建一个可以访问SomeRequest的所有字段的验证器:

    import jakarta.validation.ConstraintValidator;
    import jakarta.validation.ConstraintValidatorContext;
    
    public class SomeRequestValidator implements ConstraintValidator<ValidSomeRequest, SomeRequest> {
    
        @Override
        public boolean isValid(SomeRequest request, ConstraintValidatorContext context) {
            if (request == null) {
                return true; // Let @NotNull handle null cases
            }
    
            boolean isValid = true;
            context.disableDefaultConstraintViolation(); // Prevent default message
    
            if (request.score > 0) {
                // If score is positive, fieldPositive must be non-empty, and fieldZeroAndNegative must be null
                if (request.fieldPositive == null || request.fieldPositive.isEmpty()) {
                    isValid = false;
                    context.buildConstraintViolationWithTemplate("fieldPositive must not be empty when score is positive")
                            .addPropertyNode("fieldPositive")
                            .addConstraintViolation();
                }
                if (request.fieldZeroAndNegative != null) {
                    isValid = false;
                    context.buildConstraintViolationWithTemplate("fieldZeroAndNegative must be null when score is positive")
                            .addPropertyNode("fieldZeroAndNegative")
                            .addConstraintViolation();
                }
            } else {
                // If score is zero or negative, fieldZeroAndNegative must be non-empty, and fieldPositive must be null
                if (request.fieldZeroAndNegative == null || request.fieldZeroAndNegative.isEmpty()) {
                    isValid = false;
                    context.buildConstraintViolationWithTemplate("fieldZeroAndNegative must not be empty when score is zero or negative")
                            .addPropertyNode("fieldZeroAndNegative")
                            .addConstraintViolation();
                }
                if (request.fieldPositive != null) {
                    isValid = false;
                    context.buildConstraintViolationWithTemplate("fieldPositive must be null when score is zero or negative")
                            .addPropertyNode("fieldPositive")
                            .addConstraintViolation();
                }
            }
    
            return isValid;
        }
    }
    
    1. 将注释应用于记录

    修改SomeRequest以使用新的验证注释:

    @ValidSomeRequest
    public record SomeRequest(int score, String fieldPositive, String fieldZeroAndNegative) { }
    
    1. 在控制器中验证

    Spring Boot 在处理请求时将自动使用注释验证 SomeRequest:

    import jakarta.validation.Valid;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    class FieldValidationController {
    
        @PostMapping("/validate")
        String validate(@Valid @RequestBody SomeRequest someRequest) {
            return "Request is valid";
        }
    
    }
    

    为什么有效

    • 验证是在类级别执行的,因此所有字段都可以访问。
    • 验证逻辑score在一个地方检查两个字段及其依赖字段。
    • 使用 自定义错误消息分配给特定字段addPropertyNode(),从而提高 API 响应的清晰度。

    这种方法可确保您的请求根据分数得到正确验证,而无需每个字段进行单独的注释。

    • 1

相关问题

  • Lock Condition.notify 抛出 java.lang.IllegalMonitorStateException

  • 多对一微服务响应未出现在邮递员中

  • 自定义 SpringBoot Bean 验证

  • Java 套接字是 FIFO 的吗?

  • 为什么不可能/不鼓励在服务器端定义请求超时?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve