Springboot使用validation验证参数之一

Springboot使用validation验证参数之一_第1张图片

import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;

import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Null(message = "新增ID应为空", groups = InsertAction.class)
    @NotNull(message = "更新ID不应为空", groups = UpdateAction.class)
    private Integer userId;

    @NotEmpty(message="用户名1不能为空")
    private String name1;
    @NotNull(message="用户名2不能为空")
    private String name2;
    @NotBlank(message="用户名3不能为空")
    private String name3;

    @Email(message="非法邮件地址")
    private String email;

    @Pattern(regexp="^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$",message="身份证号不合规")
    private String cardNo;

    @Length(min=1,max=10,message="昵称长度1必须在1~10")
    private String nickName1;
    @Size(min=1,max=10,message="昵称长度2必须在1~10")
    private String nickName2;

    @Range(min=0,max=2,message="非法性别1")
    private String sex1;
    @Pattern(regexp="^([012])$",message="非法性别2")
    private String sex2;

    @Max(value=150,message="非法年龄1")
    @Min(value = 0,message = "非法年龄2")
    private int age;

    @Size(min = 1,message="至少输入一个爱好")
    List hobbies;

    @Past
    private Date birthDate;
}
public interface InsertAction {
}


public interface UpdateAction {
}


import lombok.Data;
@Data
public class ResponseResult {
    private String code;
    private String message;
    private Object result;

    public ResponseResult(Object result) {
        this.code = "200";
        this.message = "success";
        this.result = result;
    }

    public ResponseResult(String code, String message) {
        this.code = code;
        this.message = message;
        this.result = null;
    }

    public ResponseResult(String code, String message, Object result) {
        this.code = code;
        this.message = message;
        this.result = result;
    }
}

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult validationBodyException(MethodArgumentNotValidException exception){

        StringBuffer buffer = new StringBuffer();

        BindingResult result  = exception.getBindingResult();
        if (result.hasErrors()) {

            List errors = result.getAllErrors();

            errors.forEach(p ->{

                FieldError fieldError = (FieldError) p;
                log.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
                        "},errorMessage{"+fieldError.getDefaultMessage()+"}");
                buffer.append(fieldError.getDefaultMessage()).append(",");
            });
        }
        ResponseResult response = new ResponseResult("500",buffer.toString().substring(0, buffer.toString().length()-1));
        return response;
    }

}

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.groups.Default;

@RestController
@RequestMapping("/user/")
public class UserController {

    @RequestMapping("testValidation")
    public String testValidation(@Valid @RequestBody User user) {
        return "success";
    }

    @PostMapping("add")
    public String addValidation(@Validated({InsertAction.class, Default.class})  @RequestBody User user) {
        return "success";
    }

    @PostMapping("update")
    public String updateValidation(@Validated({UpdateAction.class, Default.class}) @RequestBody User user) {
        return "success";
    }
}
server.port=8090
server.servlet.context-path=/validation

Springboot使用validation验证参数之一_第2张图片

你可能感兴趣的:(SpringBoot系列,spring,framework)