Reputation: 121
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;
}
Upvotes: 3
Views: 58
Reputation: 331
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);
}
}
Upvotes: 3