SpringBoot 參數校驗

一: 通常校驗app

(0)適用場景:同一字段沒有互相矛盾的驗證策略ide

(1) 請求參數this

public class ParamsValidForm {

    @NotBlank(message = "用戶名不能爲空")
    private String userName;

    @NotBlank(message = "密碼不能爲空")
    @Length(min = 6, message = "密碼長度至少6位")
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("ParamsValidForm{");
        sb.append("userName='").append(userName).append('\'');
        sb.append(", password='").append(password).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

 

(2)controller層spa

/**
     * 1. 通常校驗
     * 場景:同一字段沒有互相矛盾的驗證策略
     */
    @PostMapping(value = "valid")
    public ServerResponse valid(@RequestBody @Valid ParamsValidForm paramsValidForm,
                               BindingResult results) {
        if (results.hasErrors()) {
            return ServerResponse.createByErrorMessage(results.getFieldError().getDefaultMessage());
        }
        return ServerResponse.createBySuccess();
    }

 

二: 分組校驗code

(0)適用場景:相同字段在不一樣場景須要不一樣的驗證策略orm

(1)請求參數blog

public class GroupsValidForm {

    @Null(message = "id必須爲null", groups = {GroupVaildDTO.SaveGroup.class})
    @NotNull(message = "id不能爲null", groups = {GroupVaildDTO.UpdateGroup.class})
    private Integer id;

    @NotBlank(message = "用戶名不能爲空")
    private String userName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("GroupsValidForm{");
        sb.append("id=").append(id);
        sb.append(", userName='").append(userName).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

 

(2)組接口接口

public class GroupVaildDTO {

    public interface SaveGroup extends Default {}

    public interface UpdateGroup extends Default {}
}

 

(3)controller層get

/**
     * 2. 分組校驗
     * 場景:相同字段在不一樣場景須要不一樣的驗證策略
     */
    @PostMapping(value = "update")
    public ServerResponse update(@RequestBody @Validated(value = GroupVaildDTO.UpdateGroup.class)
                                            GroupsValidForm groupsValidForm, BindingResult results) {
        if (results.hasErrors()) {
            return ServerResponse.createByErrorMessage(results.getFieldError().getDefaultMessage());
        }
        return ServerResponse.createBySuccess();
    }
相關文章
相關標籤/搜索