Validation with Spring MVC SimpleFormController (2)

FormView (email_basket.jsp)

 

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

<table>

                <tr>

                    <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>

                            </c:if>

                        </spring:bind>

                    </td>

                </tr>

……

</table>

</form>

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

            .getLogger("hongliang.email");

 

    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>();

        attachmentList.add(Long.parseLong(request.getParameter("id")));

        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);

            LOGGER.error(strError);

            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.

 

 

Reference:

http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/servlet/mvc/SimpleFormController.html

 

http://maestric.com/en/doc/java/spring

 

http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/validation/class-use/Validator.html

 

http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/validation/Errors.html#reject(java.lang.String)

 

http://www.javaworld.com.tw/jute/post/view?bid=42&id=152356&sty=1

 

 

Advertisements
This entry was posted in Spring. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s