Should I write custom validation or configurate spring correctly?

lor lor :

I have an entity. I use rest controller. My goal is to validate all fields in the coming JSON object. If I find one or more incorrect fields, I need to return all incorrect fields. How can I do it with spring? Should I check every field in try - catch?

@Entity
public class Client {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Size(min = 4, message = "Min length 4")
    private String first_name;

    @Size(min = 4, message = "Min length 4")
    private String last_name;

    @Size(min = 4, message = "Min length 4")
    private String fathers_name;

}
bovae :

You just need to annotate your client with @RequestBody and @Valid in rest method. Here is an example:

@RestController
@RequestMapping("/api/client")
public class ClientController {
    @PostMapping
    public ResponseEntity createNewClient(@RequestBody @Valid Client client) {
        // insert client
        return new ResponseEntity(HttpStatus.CREATED);
    }
}

If JSON data will be not valid, method will throw MethodArgumentNotValidException. You can handle it in such way:

@ControllerAdvice
public class ExceptionHandlerController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleArgumentNotValidException(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        BindingResult bindingResult = ex.getBindingResult();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=96845&siteId=1