Validation with Spring MVC SimpleFormController (2)

FormView (email_basket.jsp)


<form id="emailForm" action="/send_email.html" method="post">



                    <td class="formelement">

                        <spring:bind path="emailCommandName.recipientEmail">

                          <spring:message code="${email_validation}" text=""/>

                            <input id="recipientEmail" name="recipientEmail" value="${status.value}" type="text">

                            <c:if test="${status.error}">

                                <font color="red">${status.errorMessage}</font>








Be aware that the first time to load this page you have to load through the MVC controller rather than calling email_basket.jsp directly. Otherwise an exception of “Neither BindingResult nor plain target object for bean name ‘commanCommandName’ available as request attribute” will be caught.



Validation Class


public class EmailValidator implements Validator {

    public boolean supports(Class aClass) {

        return EmailForm.class.equals(aClass);



    public void validate(Object obj, Errors errors) {

        EmailForm form = (EmailForm) obj;


        ValidationUtils.rejectIfEmpty(errors, "recipientEmail", "field.required", "Required field");


        //Set the email pattern string

        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

        Matcher m = p.matcher(form.getRecipientEmail());

        boolean matchFound = m.matches();


        if (!matchFound) {

            errors.rejectValue("recipientEmail", "email_validation", "Invalid Email Address");



supports() define which classes to validate.  

Inside validate(), I have two validation against recipientEmail field. First one using ValidationUtil to check whether the field is empty and the second one is to check whether it is valid email address entered. If not a valid address, the method will display the error message "Invalid Email Address" on the formView page with the code reference email_validation. 


<spring:message code="${email_validation}" text=""/>

(The default error message is set to be empty, so no message will be displayed for the first load).


Controller Class


public class EmailController extends SimpleFormController {

    private static final Logger LOGGER = Logger



    public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) {


        EmailForm emailForm = (EmailForm) command;

        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession(false).getServletContext());

        EmailService emailService = (EmailService) context.getBean("emailService");

        EmailConfig emailConfig = (EmailConfig) context.getBean("emailConfig");

        ArrayList<Long> attachmentList = new ArrayList<Long>();


        String subject = emailConfig.getSubjectPrefix() + emailForm.getSenderEmail();

        Map model = new HashMap();

        boolean sendingEmail = false;


        try {

            sendingEmail = emailService.sendMail(emailConfig.getHostEmail(), emailForm.getRecipientEmail(), subject, emailForm.getMessage_optional(), attachmentList);


        catch (Exception ex) {

            String strError = "failed to send email to :" + emailForm.getRecipientEmail() + StringUtils.stackTrace(ex);


            model.put("strFeedback", "Your email could not be delivered due to sever problem");

            return new ModelAndView(this.getSuccessView(), model);



        model.put("strFeedback", "Your message has been successly sent");

        return new ModelAndView(this.getSuccessView(), model);




Workflow of SimpleFormController (in addition to the superclass):

  1. Call to processFormSubmission which inspects the Errors object to see if any errors have occurred during binding and validation.
  2. If errors occured, the controller will return the configured formView, showing the form again (possibly rendering according error messages).
  3. If isFormChangeRequest is overridden and returns true for the given request, the controller will return the formView too. In that case, the controller will also suppress validation. Before returning the formView, the controller will invoke onFormChange(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException), giving sub-classes a chance to make modification to the command object. This is intended for requests that change the structure of the form, which should not cause validation and show the form in any case.
  4. If no errors occurred, the controller will call onSubmit using all parameters, which in case of the default implementation delegates to onSubmit with just the command object. The default implementation of the latter method will return the configured successView. Consider implementing doSubmitAction(java.lang.Object) doSubmitAction for simply performing a submit action and rendering the success view.

According to the workflow, the validation will be carried before onSubmit() via processFormSubmission(). If validation failed, you will be returned to formView page (email_basket.jsp) with error message displayed. If validation successed, the overridden onSubmit() method will be called and you can have your code here to run some functions.






This entry was posted in Spring. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s