Himu\’s Attempt at Blogging

Tidbits from my thoughts

Spring MVC Error Handling

leave a comment »

This is not a tutorial of any sort. I’m adding this post to record the error-handling techniques of Spring MVC.

Catching

Errors can be caught in two places:

  1. Inside a validator (extended from Validator)
  2. Inside a controller

1. Validator

In the validate() overridden method, we can use two approaches:

a) Using the errors object:

errors.rejectValue(field, code, defaultMessage) → for field errors
errors.reject(code, defaultMessage)  → for global/general errors

b) Using ValidationUtils.rejectXxx(…) methods

2. Controller

In the onSubmit(request, response, command, BindException errors) overridden method:

errors.rejectValue(field, code, defaultMessage) → for field errors
errors.reject(code, defaultMessage)  → for global/general errors

return new ModelAndView(getFormView(), errors.getModel())

getFormView() returns us to the input form. The call to errors.getModel() is crucial here.

Reporting with JSP

<form:form command=”commandNameIfChangeFromDefault”>
<span class=”…”>
<spring:hasBindErrors name=”command”>
<c:forEach items=”${errors.allErrors} var=”error”> <!– or errors.globalErrors or errors.fieldErrors –>
<spring:message code=”${error.code}” text=”${error.defaultMessage}”/>
</c:forEach>
</spring:hasBindErrors>
</span>
</form:form>

Advertisements

Written by mhimu

September 27, 2010 at 3:41 pm

Posted in Java, spring

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

%d bloggers like this: