简体   繁体   中英

How does spring MVC do form validation (using hibernate)

I am following a tutorial, that showed us how to build using Spring MVC framework a simple form that can be validated.

We created a function annotated using RequestMapping then added @Valid as annotation to the first argument of this function along side @ModelAttribute annotation. Let's call the first argument type ClassA .

Now in ClassA we annotated some of its properties with hibernate validation annotations (eg @NotNull , @Pattern , etc...)

What I am trying to understand is how is this all working?

I checked the code for @interface NotNull for example and it really does nothing.

I am assuming that the spring MVC framework, uses reflection to detect that the first argument of the RequestMapping function is annotated using Valid , then when the form is submitted is calls SOMETHING to validate ClassA properties.

Where is this SOMETHING ? Is it in hibernate? Code please... How did Spring figure out to call hibernate code, we just added the hibernate jars to the project but at no point we told Spring to use them.

Also, what is the specification that binds Spring MVC to hibernate?

Can someone is simple terms and using high level (and references of code if possible) explain to me how things are working?

I am very new to this and coming from C++ where things are done very differently. I am trying to understand the mechanisms behind the workings of Spring .

What you are seeing is Spring's support to JSR-303 Bean Validation API . Those annotations such as @NotNull , @Pattern are all part of this JSR. Since this is just a JSR (basically, JSR is just a set of interfaces), it needs a concrete implementation in order to actually work (called the provider). Here is where hibernate comes in the picture. Hibernate owns an implementation of JSR-303, called the hibernate-validator . This API has nothing to do with the core ORM functionalities of Hibernate. In fact, this API is the reference implementation of JSR-303, that is why in the documentation you will see that it is used as the default provider.

So as the user of Spring framework, all you need to know is Spring needs to find an implementation of JSR-303 in the classpath so that you can start using those annotation from javax.validation.* package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM