denis
denis

Reputation: 1473

Spring 3.1 MVC - Form handling workflow best practice

At the moment I am trying to get to know the correct workflow for form submission/validation/error handling in Spring MVC 3.1. No I got some questions.

  1. What is the correct way of preserving the form errors, bound model through a redirect (is there a built in way - I haven't found one)
  2. I know that I can use the Spring form tags and JSR 303 to validate (including i18n messages) submitted form values. But what is the correct way of handling errors that happen while processing the given values? (e.g. registration is not possible - email already registered) From Struts or non java Frameworks I know something like ActionErrors. What is the correct way of doing it in Spring MVC?
  3. What is the correct way of iterating through the form errors available via the "form:errors" tag? I just want to show a list of errors.

Upvotes: 3

Views: 3617

Answers (2)

anton1980
anton1980

Reputation: 1009

1) In Spring 3.1 you can use RedirectAttributes. They were designed specifically for Post/Redirect/Get screnario. You can see a great example here: Spring - Redirect after POST (even with validation errors)

2) I think JSR-303 validators were meant to be simple, self-reliant, and independent from each other. While it may be possible to write them in such a way that they access other persistence entities, etc - it is not a best practice. I personally check for duplicate emails in the controller. If the email already exists - I add a new FieldError to the BindingResult.

Upvotes: 1

Jose Luis Martin
Jose Luis Martin

Reputation: 10709

From reference documentation:

1.) Use FlashMap attributes from RequestContextUtils.

2.) When using the MVC namespace a JSR-303 validator is configured automatically assuming a JSR-303 implementation is available on the classpath.Any ConstraintViolations will automatically be exposed as errors in the BindingResult renderable by standard Spring MVC form tags.

3.use path="*" to list all errors

<form:form>
      <form:errors path="*" cssClass="errorBox" />
      <table>
          <tr>
              <td>First Name:</td>
              <td><form:input path="firstName" /></td>
              <td><form:errors path="firstName" /></td>
          </tr>
          <tr>
              <td>Last Name:</td>
              <td><form:input path="lastName" /></td>
              <td><form:errors path="lastName"  /></td>
          </tr>
          <tr>
              <td colspan="3">
                  <input type="submit" value="Save Changes" />
              </td>
          </tr>
      </table>
  </form:form>

Upvotes: 4

Related Questions