Spring @Valid 和 @Validated 的区别和使用

分组示例

public interface First{}

public interface Second{}

public class User {

// 所有都验证

@NotNull(message = "...")

private int id;

// First 才验证

@NotNull(message = "...", groups = { First.class })

private String username;

// First 或 Second 才验证

@NotNull(message = "...", groups = { First.class, Second.class })

private String content;

// First 验证 NotEmpty,Second 验证 Size

@NotEmpty(message = "...", groups = { First.class })

@Size(message = "...", min = 3, max = 8, groups = { Second.class })

private String height;

}

// 只验证 Second 分组和没有分组的属性

public String save(@Validated( { Second.class }) User user, BindingResult result) {

if (result.hasErrors()) {

return "validate/error";

}

return "redirect:/success";

}

分组序列

public interface GroupA {}

public interface GroupB {}

@GroupSequence( { GroupA.class, GroupB.class })

public interface Group {}

public @ResponseBody String save(@Validated({ Group.class }) User user, BindingResult result) {

if(result.hasErrors()) {

return false;

}

return true;

}

嵌套验证

public class Item {

    @NotNull(message = "id不能为空")

    @Min(value = 1, message = "id必须为正整数")

    private Long id;

@Valid

    @NotNull(message = "props不能为空")

    @Size(min = 1, message = "至少要有一个属性")

    private List props;

}

public class Prop {

    @NotNull(message = "pid不能为空")

    @Min(value = 1, message = "pid必须为正整数")

    private Long pid;

    @NotNull(message = "vid不能为空")

    @Min(value = 1, message = "vid必须为正整数")

    private Long vid;

    @NotBlank(message = "pidName不能为空")

    private String pidName;

    @NotBlank(message = "vidName不能为空")

    private String vidName;

}

@RestController

public class ItemController {

    @RequestMapping("/item/add")

    public void addItem(@Validated Item item, BindingResult bindingResult) {

        doSomething();

    }

}

验证多个对象

@Controller 

public class PeopleController { 

    @RequestMapping("/add") 

    public @ResponseBody String add(@Validated People pp, BindingResult result1, @Validated Person ps, BindingResult result2) 

    { 

        if(result1.hasErrors()) 

        { 

            return false; 

        } 

        if(result2.hasErrors()) 

        { 

            return false; 

        } 

        return true; 

    } 

}

亚马逊测评www.yisuping.com

你可能感兴趣的:(Spring @Valid 和 @Validated 的区别和使用)