Validation for Hibernate in Spring 3 Web MVC (with Netbeans)

This blog details how to apply Validation to Spring 3 Web MVC forms using Hibernate’s validation framework.

Initial setup of a Spring 3 Web MVC project that uses Hibernate is detailed in this tutorial. This tutorial expands on the project created in that tutorial.

( The project in that tutorial uses Netbens but can easily be ported to eclipse.)

Firstly, create the project detailed in the afore mentioned tutorial here.

Download the Hibernate validation jar files from here: http://sourceforge.net/projects/hibernate/files/hibernate-validator/ and add them to the project by right clicking on the ‘libraries’ folder and choosing ‘Add Jar/Folder…’.

There are two main jar files ‘hibernate-validator-4.2.0.Final.jar’ and ‘hibernate-validator-annotation-processor-4.2.0.Final.jar’. Add the both of them.

Within the Hibernate Validation distribution folder, there are folders called ‘lib/required’. This folder contains a few additional jar files. Add them to the project/classpath also as they are required as dependencies of Hibernate Validation.

The existing project uses the Hibernate library shipped with Netbeans (7.1.1). It’s probably best to remove the library and download and use the latest hibernate jar files available from here. Ditto for all other Netbeans Libraries used.

Now that the Hibernate Validation jar files have been added to the Spring 3 Web MVC project, coding can begin.

Update TBlog.java with the following @NotBlank annotations:

 

Update BlogController.java 

  • The @Valid annotation tells Spring to validate the TBlog.
  • The results of the validation are contained within the BindingResult.
  • This code checks for the existence of validation errors and returns to the ‘edit’ form if any validation errors are present. If no validation issues, then the TBlog object is saved.
  • Note that it is not necessary to populate the ModelMap with new data, the existing form data is retained.

Now, in the edit form, we need to show these validation errors:

blog/edit.jsp

  •  It is critically important that commandName=”TBlog” is the same as @ModelAttribute(“TBlog“) for this to work properly. (“TBlog” = “TBlog”). Without this matching, it will half work so to speak…..
  • Note also that <form:errors ‘path’ attribute matches the form Bean (TBlog.java in this case) member name.
  • <form:errors path=”*” will render all error messages. The element type is ‘p’ for <p> html paragraph, it could be ‘div’ for example also.

To accommodate this, some simple CSS rules are also added to css/styles.css

 

Different types of validation attributes

The above example demonstrates the @NotBlank annotation. Other available annotations are available here in the Hibernate Java Docs:

The difference between @NotBlank and @NotEmpty is that @NotBlank does not allow white space characters only. i.e. it does a .trim() before checking.

Custom messages

At this stage, it’s possibly something of a mystery as to where the error  messages on the form are coming from, i.e. “may not be empty”. This is the default error message, to change it, do the following:

In “dispatcher-servlet.xml”, add the following bean:

Now create a .properties file in the default package in “Source Packages”. From the XML snippet above, it may be clear that the name of the default .properties file should be “messages.properties” to match the bean declaration.

Now Hibernate Validation will look to this properties file for key codes. The problem now is, how to know what the property key’s should be?

To see this, modify BlogController.java

The code “For demonstration purposes only” prints out the key codes being looked for. In this case, the key codes are:

Where

NotBlank is the Annotation name

TBlog is the @ModelAttribute(“TBlog“) which of course must match the commandName=”TBlog” in the form.

title and content are the property names from TBLog.java

And there  you have it, in four simple steps, validation can be added to a Spring Hibernate project.

  1. Annotate the form Bean
  2. Ensure @ModelAttribute(“TBlog“) matches the commandName=”TBlog
  3. Add the bean declaration to the application context (servlet-context.xml) in this case
  4. Create a matching .properties file in the class path containing keys for the validation

Comments always welcome…..

 

 

 

 

 

4 Comments

  • Pingback: viagra
  • Whenever trying to create new blog with validation it gives this error

    description The server encountered an internal error () that
    prevented it from fulfilling this request.

    exception

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path ‘/blog/edit’: {public java.lang.String com.outbottle.springhibernate.controllers.BlogController.edit(com.outbottle.springhibernate.model.entities.TBlog,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap,javax.servlet.http.HttpServletRequest), public java.lang.String com.outbottle.springhibernate.controllers.BlogController.edit(com.outbottle.springhibernate.model.entities.TBlog,org.springframework.ui.ModelMap)}. If you intend to handle the same path in multiple methods, then factor them out into a dedicated handler class with that path mapped at the type level!
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    root cause

    java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path ‘/blog/edit’: {public java.lang.String com.outbottle.springhibernate.controllers.BlogController.edit(com.outbottle.springhibernate.model.entities.TBlog,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap,javax.servlet.http.HttpServletRequest), public java.lang.String com.outbottle.springhibernate.controllers.BlogController.edit(com.outbottle.springhibernate.model.entities.TBlog,org.springframework.ui.ModelMap)}. If you intend to handle the same path in multiple methods, then factor them out into a dedicated handler class with that path mapped at the type level!
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodResolver.resolveHandlerMethod(AnnotationMethodHandlerAdapter.java:600)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    • Hmmmm, I’m not sure to be honest. I tried to reproduce it to no avail. I think it may have something to do with having two controller methods with the same RequestMapping signature.

      @RequestMapping(value=”/edit”, method=RequestMethod.POST)

      Perhaps post your complete controller code here and I can take a look.

      Thanks