javaspring中的自定义验证

mm9b1k5b  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(334)

我对java非常陌生,我刚刚创建了一个spring引导应用程序来进行一些练习。
我创建了一个用json接收post请求的控制器:

{
   "team1": {
     "score": 10,
     "colour": "RED"
   },
   "team2": {
     "score": 3,
     "colour": "BLUE"
   }

}

控制器:

public @ResponseBody
    ResponseEntity<Response<Game>> saveGame(
            @Valid @RequestBody PostedGameRequest postedGameRequest
    ) {
    // ...
}

postedgamerequest得到验证,这很正常,但是有两个属性:类型为postedgamerequestteam的team1和team2,它们没有得到验证。我加了一些 @NotEmpty 属性在里面,但那不起作用。
所以现在我创建了一个定制的teamvalidator,它验证团队中的字段,但是当它失败时,它将只显示我在 @Team 属性类。如果我能自己验证每个字段就好了。

@Builder
public class PostedGameRequest {
    @Team()
    private final PostedGameRequestTeam team1;

    @Team()
    private final PostedGameRequestTeam team2;

    public PostedGameRequestTeam getTeam1() {
        return team1;
    }

    public PostedGameRequestTeam getTeam2() {
        return team2;
    }

}
public class TeamValidator implements ConstraintValidator<Team, PostedGameRequestTeam> {

    List<String> colours = Arrays.asList("RED","BLUE");

    @Override
    public boolean isValid(@Valid PostedGameRequestTeam team, ConstraintValidatorContext context) {
        if (team == null || team.getColour() == null || team.getScore() == null) {
            return false;
        }

        if (team.getScore() < 0 || team.getScore() > 11) {
            // This will only lead to an invalid team message, should get a message about the score in this case
            return false;
        }

        if (!colours.contains(team.getColour())) {
            // This will only lead to an invalid team message, should get a message about the colour in this case
            return false;
        }

        return (team.getId() != null || team.getName() != null);
    }
}

我有一种感觉,我做这件事不是我应该做的。为什么我的第一种方法不起作用?有什么我必须添加的,使验证器也运行的team1和team2属性没有我添加一个自定义验证器 @Team ?

au9on6nz

au9on6nz1#

而不是 @NotEmpty 尝试

@NotNull

这将确保team1和team2始终包含一个不为null的对象
如果您想对team1和team2的每个属性进行更多的验证,请在java中进入该对象并向这些字段添加更多注解。对于 string 可以添加的属性

@NotNull
@Size (min = 1)

这将确保它始终包含一个值
另外,要进入验证的一步,只需添加 @Valid 所以你的目标会变成

public class PostedGameRequest {

    @NotNull
    @Valid
    private final PostedGameRequestTeam team1;

    @NotNull
    @Valid
    private final PostedGameRequestTeam team2;

然后在里面

public class PostedGameRequestTeam {

@Min(0)
integer score;

@NotNull
@Size (min=1)
String color;

}

编辑: @Size 仅适用于字符串字段,不适用于自定义对象

68bkxrlz

68bkxrlz2#

而不是用你的 @Team 处理所有验证逻辑的自定义验证器(我认为在本例中这不是很有用),您应该在每个验证器中分别声明您的验证注解 PostedGameRequestTeam 对象。

public class PostedGameRequestTeam {

  @NotBlank(message = "The team colour value must not be null, empty or blank!")
  @TeamColour(message = "The team colour must be RED or BLUE")
  private String colour;

  @Min(value = 0, message = "The score value must be higher than 0!")
  @Max(value = 11, message = "The score value must be lesser than 11!")
  private Integer score;

  // Getters and Setters
}

注意我用了 @Min 以及 @Max 注解,那是因为 javax.validation.constraints.Size 仅验证字符串的长度。
现在可以添加的自定义约束验证 @TeamColour .

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Constraint(validatedBy = { StatusNotaFiscalValidator.class })
public @interface TeamColour {

    String message() default "The team colour must be RED or BLUE!";

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

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

}

public class TeamColourValidator implements ConstraintValidator<TeamColour, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean valid = true;

        if (value != null) {
            if (!value.equals("BLUE") && !value.equals("RED")) {
                valid = false;
            }
        }

        return valid;
    }

}

然后,你应该加上 @NotNull 属性,以便验证具有 team 对象。

@Builder
public class PostedGameRequest {

    @NotNull
    @Valid
    private final PostedGameRequestTeam team1;

    @NotNull
    @Valid
    private final PostedGameRequestTeam team2;

    public PostedGameRequestTeam getTeam1() {
        return team1;
    }

    public PostedGameRequestTeam getTeam2() {
        return team2;
    }

}

public @ResponseBody
    ResponseEntity<Response<Game>> saveGame(
            @Valid @RequestBody PostedGameRequest postedGameRequest
    ) {
    // ...
}

此逻辑处理您要使用的所有级联验证。

相关问题