I'm working on a Ninja JSON-based application in which I am implementing @JSR303Validation annotations across multiple controller methods. I'm currently checking validations in the controllers themselves by passing in the Validation object and calling validation.hasBeanViolations()
to see if there are failures. If there are, I'm returning a failing Result to the client.
Rather than doing this in the controller, I would like to validate requests using a Filter. However, I'm at a loss as to how to go about doing this? Could somebody help? As far as I can tell, you can't pass validations to a filter as a parameter, and the context.getValidation() object does not seem to be catching any validation failures.
That's currently not possible using a Filter (as of Ninja 4.0.x). However, you can implement it yourself. That would work roughly the following way:
Get the contents of the incoming request via
context.getParameterAs("parametername", Pojo.class);
Validate the class yourself using
javax.validation.Validation
. You can more or less copy and paste the approach from JSRValidator (https://github.com/ninjaframework/ninja/blob/develop/ninja-core/src/main/java/ninja/validation/Validators.java).That's not too complicated. But it's not as automagic as annotating methods in the controllers.