Here is a simple Spring MVC guestbook form complete with validation error messages:
To code this, firstly add hibernate-validator to your classpath (pom.xml):
org.hibernate hibernate-validator 4.3.1.Final
And we’ll code the form as a java class. Notice we added few validators using annotations provided by hibernate-validators. The associated error message is also coded here :
public class MessageForm { (message = "Please provide your name") private String name; (message = "Please provide your email") (message = "Invalid email address") private String email; (min = 10, message = "Please enter at least 10 characters") private String message; // getters & setters.. }
Next we’ll create the JSP view containing html code for the form. Notice the usage of
On our controller class, the method that serves the guestbook form first checks if the model attribute “messageForm” exists before creating a new one. This is to cover the scenario where validation fails and user has to be redirected back :
public class GuestbookController { /** * Serve guestbook form. */ (value = "/", method = RequestMethod.GET) public String home(Model model) { if(!model.containsAttribute("messageForm")) model.addAttribute("messageForm", new MessageForm()); return "guestbook"; } // more code .. }
On the message submission handler, notice the usage of annotation. This will trigger validation declared using annotation on our form class above. Validation errors can be checked from the associated BindingResult object. Here if error occurs we redirect the user back to the form and display the error messages (pay attention to the “redirect:” prefix). Notice the BindingResult object is passed via RedirectAttributes using org.springframework.validation.BindingResult.messageForm name, this will ensure the messages can be accessed using
... /** * Form post handler */ (value = "/", method = RequestMethod.POST) public String send( ("messageForm") MessageForm messageForm, BindingResult binding, RedirectAttributes redirectAttributes) { // Redirect back into form page if errors detected if (binding.hasErrors()) { redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.messageForm", binding); redirectAttributes.addFlashAttribute("messageForm", messageForm); return "redirect:/"; } return "redirect:/result"; } ...
And finally display a success message if no errors
... /** * Result page, simply displays 'message has ben sent' */ (value = "/result", method = RequestMethod.GET) public String result() { return "result"; } ...
Get The Source Code
Source code for this blog is available to checkout via git:
git clone https:///gerrytan/formvalidation1.git
To run it, simply use mvn clean tomcat:run, and point your browser to http://localhost:8080/formvalidation1
Thanks Oscar for describing the BindingResult preservation techniques on redirection.
Exactly what I was looking for. Works perfectly.
Thank you for your work!