Exception handling and form validation
When submitting a form, it should validate the form data before it is stored in the backend database.
Form binding and validation
Like Spring MVC, Struts, Stripes, JSF etc. MVC provides the similar progress to process form submission.
Gather user input form data.
Convert form data to the target form bean. If there are some conversion failure, it is possible to stop the progress and notify user.
Bind the converted value to the form bean.
Validate the form bean via Bean Validation. If there are some constraint violations, it is possible to stop the progress and notify user.
Continue to process form.
MVC provides a BindingResult
to gather all of the binding errors and constraint violations in the request.
Handling form validation
Inject it in the controller class.
In the controller method, add @Valid
annotation on the method parameters.
If the validation is failed, the isFailed
method should return true
.
You can iterate all violations(validationResult.getAllViolations()
) and gather the violation details for each properties.
Then display the error messages in the JSP pages.
Handling exception
Like JAX-RS exception handling, you can handle exception via ExceptionMapper
and display errors in the certain view.
Create a custom ExceptionMapper
and add annotation @Provider
.
Different from JAX-RS, the entity value is the view that will be returned. In the error.jspx file, display the error
model via EL directly.
When the TaskNotFoundException
is caught, it will display the erorr like the following.
Source codes
Clone the codes from my GitHub account.
Open the mvc project in NetBeans IDE.
Run it on Glassfish.
After it is deployed and running on Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in browser.
Last updated