Friday, May 24, 2013

Spring MVC Form Validation with Annotation using Spring Bean Validation Framework

This tutorial walks you through the step by step instructions in order to support and apply validation example in Spring MVC, using Spring Bean Validation Framework, which is part of the Spring Modules project.

So here's my record so I don't forget in future how I did it.

Make sure that you have downloaded the spring-modules-validation-0.8.jar have it in your classpath.

Spring Modules validation provides a bunch of generic validation out of the box for all the tedious, standard stuff - length validation, mandatory fields, valid e-mail addresses etc (details here). And you can plug this straight into your application by using annotations. How? Easy.

Below is the configuration, you have to do in your servlet xml file, where you are defining your validator.





Below is my simple Entity Model class, which deals with product. Since the Name and Description of the Product is a must while presisting the data, i have added an validation constraint through annotation, here you can see i have added @NotBlank for name and description variables, and also the message to be shown to the users when they left it blank.

public class Product{
 
    @Id
    @Column(name="ID")
    @GeneratedValue
 private int id;
 
 @NotBlank(message = "Name should not be empty")
 @Column(name="NAME")
 private String name;
 
 @NotBlank(message = "Description should not be empty")
 @Column(name="DESCRIPTION")
 private String description;
 
 public int getId() {
  return id;
 }
....

Now the Spring Controller
The Bean Validation Framework includes its own Validator implementation, called BeanValidator, we are injecting this into the controller, and it was autowired through the xml configuration which we did in the top.

On submitting the form, we will be routed to the addExpense method, where will call the validate() method by passing in the form bean (expense) and the BindingResult. If there any errors, we will just return the form view name which will show the error message.

@Controller
public class ExpenseController 
{
 @Autowired
 private ExpenseService expenseService;
 @Autowired
 private ExpenseTypeService expenseTypeService; 
 @Autowired
    private Validator validator;
    
    public void setValidator(Validator validator) {
        this.validator = validator;
    }
 
 @RequestMapping("/expenselist")
 public String expenselist(Map map, @ModelAttribute("ExpenseName") String expenseName)
 {
  List expenseTypeList = expenseTypeService.fetchAll();
  
  map.put("expense", new Expense()); 
  map.put("expenseTypeList", expenseTypeList);
  map.put("expenseList", expenseService.fetchAll()); 
  map.put("expenseName", expenseName);
  return "expenselist";
 }
 
 @RequestMapping(value="/addexpense", method=RequestMethod.POST)
 public String addExpense(@ModelAttribute("expense") 
   Expense expense, BindingResult result, RedirectAttributes redirectAttrs)
 {
  validator.validate(expense, result);
  if (result.hasErrors()) { return "expenselist"; }
  
  //System.out.println(expense.getExpenseTypeId());
  System.out.println(expense.getName());
  expenseService.add(expense);
  redirectAttrs.addFlashAttribute("ExpenseName", expense.getName());
  return "redirect:/expenselist.html";
 }
}

Suppose if you are not Injecting the Validator, you can just initilize the valiator as shown below in the controller, rest are same as above
public class ExpenseController 
{
 @Autowired
 private ExpenseService expenseService;
 @Autowired
 private ExpenseTypeService expenseTypeService;

        private BeanValidator beanValidator = new BeanValidator(new AnnotationBeanValidationConfigurationLoader());

}

Below is the screen shot, with the error message shown, when the form is submitted.



The tag form:errors will help us to show the error message to the users

Expense :


Amount :


ExpenseType :


Date Incurred :


Description :





Happy programming.

No comments:

Post a Comment