中的值列表>驗證彈簧中的值列表涉及利用Spring的驗證框架,特別是使用@Valid
和自定義驗證註釋的註釋。 該方法取決於列表的性質和驗證規則。 如果您要驗證列表中的簡單數據類型(例如整數,字符串),則通常可以依靠內置約束。但是,對於更複雜的驗證方案或針對預定義集的驗證,通常需要進行自定義驗證器。
>直接驗證簡單數據類型的直接方法涉及使用@NotNull
>,@Size
>,@Min
,@Max
,
public class MyObject { @NotNull @Size(min = 1, max = 10) //Example size constraint private List<@Min(0) @Max(99) Integer> myIntegerList; //Getters and setters }
ConstraintViolation
>我如何確保使用Spring驗證的列表字段中只允許特定值?
@Constraint(validatedBy = AllowedValuesValidator.class) @Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface AllowedValues { String message() default "Invalid value in list"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String[] values(); }
接下來,創建驗證器類:
public class AllowedValuesValidator implements ConstraintValidator<AllowedValues, List<?>> { private String[] allowedValues; @Override public void initialize(AllowedValues constraintAnnotation) { this.allowedValues = constraintAnnotation.values(); } @Override public boolean isValid(List<?> values, ConstraintValidatorContext context) { if (values == null) return true; //Consider null as valid for (Object value : values) { boolean found = false; for (String allowedValue : allowedValues) { if (value.toString().equals(allowedValue)) { found = true; break; } } if (!found) { return false; } } return true; } }
public class MyObject { @AllowedValues(values = {"value1", "value2", "value3"}) private List<String> myStringList; //Getters and setters }
最後,將自定義註釋應用於列表字段:<>> <> <>myStringList
NullPointerExceptions
<🎜 任何其他值都會觸發驗證錯誤。 請記住要適當處理潛在的
,如示例所示。null
。 根據應用程序的要求,確定應視為有效或無效的列表。 NullPointerExceptions
<> null
BindingResult
FieldError
public class MyObject { @NotNull @Size(min = 1, max = 10) //Example size constraint private List<@Min(0) @Max(99) Integer> myIntegerList; //Getters and setters }
>對象包含pom.xml
對象的列表,每個對像都代表失敗的驗證。 您可以在控制器中訪問這些錯誤並返回適當的響應。 您可以自定義錯誤處理以適應您的應用程序的需求。例如,您可以返回帶有詳細錯誤信息的JSON響應,也可以使用更複雜的錯誤處理機制(例如異常處理和自定義異常類)。 考慮使用Hibernate Validator之類的驗證框架以獲得更高級的功能,並與Spring更好地集成。請記住,如果您尚未使用它,請在您的
以上是如何在春季驗證價值清單的詳細內容。更多資訊請關注PHP中文網其他相關文章!