javax.validation - BindingResult

1. Writing the received parameter object parameters, using @ NotBlank, @ NotNull annotation
javax.validation.constraints.NotBlank Import; 
Import javax.validation.constraints.NotNull;

@Data
public class AbcParam {

@NotBlank (the Message = "Course name can not be")
Private String title;

@NotNull (the Message = "price can not be empty ")
Private Integer. price;
}

2. use Controller Write enable @Valid parameter check, and the BindingResult parameter (action: With the parameter, the parameter still be injected into the distal abcParam, parameter validation fails does not throw 400, bindingResult parameters include authentication failure information)
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
@RestController
@RequestMapping(value = "/abc")
public class AbcController {
  @PostMapping(value = "/save")
  public Object save(@RequestBody @Valid AbcParam abcParam, BindingResult bindingResult){

  boolean hasErrors = bindingResult.hasErrors();
  if(hasErrors){
  List<String> errorMsgList = new ArrayList<String>();
  List<FieldError> errors = bindingResult.getFieldErrors();
  for (FieldError error:errors) {
  String errorMsg = error.getDefaultMessage();
  errorMsgList.add(errorMsg);
  }
     return errorMsgList;
  }
  return abcParam;
  }
}

3. Test, will enter the controller

Guess you like

Origin www.cnblogs.com/abdusalam10/p/11888542.html