Announcement Announcement Module
No announcement yet.
How do I deal with non-validation errors in Spring MVC? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • How do I deal with non-validation errors in Spring MVC?

    I am using commons validator in spring MVC for form validation. I am able to show validation errors using <spring:bind> tag. All good so far! However, I need a way to add and display non-validation error on a page.

    How do I display general errors that are not bound to a field?

    I was using ActionErrors is struts to add and display errors on a page for both validations and other types of errors. Is there an equivalent feature in Spring MVC?

  • #2
    The <spring:bind> tag has support for global errors as well as ones bound to a field. My guess is that you'd like to set a global error as a result of some logic in the form controller.

    In this case, in your controller you'd want override an onSubmit method that passes in a BindException. From there you can set your global error.

    errors.reject&#40;"databaseerror", "There was a database error, please try your request again later."&#41;;
    Map model = errors.getModel&#40;&#41;;
    return new ModelAndView&#40;getFormView&#40;&#41;, model&#41;;
    In the FormView() JSP you can get the global errors by binding to the backingObject name, without any fields specified.

    <spring&#58;bind path="priceIncrease">
        <c&#58;forEach items="$&#123;status.errorMessages&#125;" var="error">
              <font color="red"><c&#58;out value="$&#123;error&#125;"/></font><br>
    As I tried out this example I found it a bit unfortunate that you can't set a global error by name. You can set field level errors, however those fields must exist in your backingObject. Or you can add to a list of general errors. You can't specify a general error by name though.

    I would vote for the addition of some rejectGlobal methods that take the same arguments as rejectValue (only in global scope).

    Until then you'll need to do some JSP hackery if you want to do something special with the global errors.



    Or, instead of JSP hackery, you can fudge your backingObject. Add some named global error fields, i.e., globalDBError, globalUserNotFound, etc. Your form will never set or read these value, but you'll be able to register errors against them. I'd much rather have my rejectGlobal interface, but it's not there and I hate doing complex logic in JSP. This hack seems somewhat more elegant than JSP if/else tags.

    <spring&#58;bind path="priceIncrease.globalDBError">
      <font color="red"><c&#58;out value="$&#123;status.errorMessage&#125;"/></font><br>


    • #3
      Worked like a charm.


      • #4
        Related to this, Spring 1.2 also adds an 'addAllErrors" method to the Errors interface you can use to merge several Errors objects into one.