In this example we will tackle Spring MVC 3 Form processing. You will learn the basic concept of Spring MVC 3 Forms. In this application a user can register a new book by submitting a form. After the form is submitted we can process them and print them back out. And if this where a real application, you'll probably save them to some database or persistent storage. The SimpleFormController here is deprecated but it is useful for this example because I'm addressing xml based configuration, I prefer annotation based configuration which you can find here.




Maven configuration


You need the following jar files. So either add this pom.xml file to your application or download and add the jar files to your class-path.




messages.properties


This typeMismatch.price message is used if an incorrect price is filled in.


typeMismatch.price= Price field is invalid. Please enter a number.


SimpleFormController


Our controller extends SimpleFormController class for form processing using xml configuration. The constructor sets the Book class and names the book model attribute as "BOOK". Spring will then create an instance of the Book class and Spring will associate it with the form with model name "BOOK". If we override the onSubmit method of SimpleFormController we are able to receive the data of the form. If the form contains any errors Spring will throw the errors back to the page. (Remember the message.properties file?) - If the form is valid we can assign it directly to the Book Object.


package org.camelcode.controller;

import org.camelcode.model.Book;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class RegistrationController extends SimpleFormController {

    public RegistrationController(){
        setCommandClass(Book.class);
        setCommandName("BOOK");
    }

    @Override
    protected ModelAndView onSubmit(Object command, BindException errors) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        if (errors.hasErrors()){
            modelAndView.setViewName("RegisterNewBook");
        } else {
            Book book = (Book)command;
            modelAndView.setViewName("Confirmation");
            modelAndView.addObject("book", book);
        }
        return modelAndView;
    }
}


Screenshots


Spring-MVC-Form-RegisterNewBookValidation



Spring-MVC-Form-RegisterNewBook



Spring-MVC-Form-RegisterNewBookSuccess