D
D
Dobby Free2017-08-16 15:29:55
Java
Dobby Free, 2017-08-16 15:29:55

How to properly organize data validation?

I would like to simply, with a minimum of code, validate data in the spring controller. Googled, but so far I have not found a suitable and working solution. I would like it to be like this:
1. All validation is based on annotations, without additional validator classes for each model (I saw such annotations in javax.validation.constraints there).
2. It is advisable not to hang anything extra on the actions in the controller (I mean, for example, BindingResult in the parameters - I would not really like to prescribe this in each method). It is advisable to simply make it so that, for example, hang the Valid annotation on the parameter and if the data is not valid, then when the action is called, it would immediately knock out an error, and something like "status: error, errors: [ error1, error2 ]" would come to the front (in json). Perhaps you need to make some kind of global exception handler to catch validation errors and return them in this format.
3. I would also like to call any action in the controller with a successful operation (no errors) to return "status: success, result: {result}" (in json, in place of {result}, respectively, the result of the method, if it was not void - then this field simply should not be or null). But again, in order not to prescribe this for each method, but simply to make some kind of global interceptor somewhere (not only exceptions, but xs even what to call it ... successful completions)
Please tell me how to organize this? Preferably with examples.
PS Just do not send me to Google, I have not found anything suitable there yet! :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kosarev, 2017-08-17
@jaxtr

To get started, read the Spring documentation . Everything is maxed out.

  1. Additional validator classes are required only for special cases. In general, you can limit yourself to annotations from Java Bean Validation and its implementations.
  2. Actually, the results of validation are collected in BindingResult . And the validation errors that you then send to the front are taken from it.
  3. What? Are you too lazy to write return ResponseEntity.ok() at the end of each method ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question