3

This is a follow-on to my question Spring Web MVC - validate individual request params.

I've figured out how to invoke the Spring Validator on domain objects that have been created from my inputs and how to have that validator honor the JSR-303 annotations on my classes themselves. The part I can't figure out is where in my code to perform this validation. The obvious approach is to do it in the controller and return a different model and view if there's a validation failure.

But I also have a service layer which sometimes gets calls to create/update objects from input sources other than the web controller. So it's tempting to implement validation there, but the only obvious way I can think of to report a failure is throw an exception. I see Spring provides BindException but the Javadoc also basically says not to use it in application code.

What is the common/recommended practice here?

Community
  • 1
  • 1
Dan
  • 10,990
  • 7
  • 51
  • 80

4 Answers4

7

I think the answer is both.

Controllers are associated with views. You don't want the validation to disappear if you change view technologies.

Services should assume that no one is safe and validate all incoming parameters.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Fair enough. But in that case, is there a clean way to report the failure? – Dan Jun 06 '11 at 15:07
  • Report to whom? The web user? The controller does that. The app server? The service should do that in the log or an alert or something else. I'm assuming that the exception will not propagate out of the controller. – duffymo Jun 06 '11 at 15:59
2

Other answers are all good, I'll just state one important rule:

Each subsystem/layer should validate its input, no matter where it comes from.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

When you encapsule the validation logic inside of a ValidationService you can use it inside your controllers and services. As you want the user to interact with the input and to correct invalid information you should be able to display validation problems in your web view.

Sometimes you might have data (CommandObjects, Forms) which is not directly visible in the service layer and then the validation should be done in the controller which then passes the information into the service layer.

When you design your application you should think about the interaction between each layer. Mixinig validation logic into every layer might not be needed. Think about how data gets into your system. If controllers are your main entry point you can perfectly place it there since no data gets into your services without passing the validation.

laufzeit
  • 116
  • 4
0

At least you should validate inputs at the service layer, in order to guarantee correctness. Additionally you can do validations further up to get better usability, etc. if needed.

gpeche
  • 21,974
  • 5
  • 38
  • 51