When submitting a form, it should validate the form data before it is stored in the backend database. git
Like Spring MVC, Struts, Stripes, JSF etc. MVC provides the similiar progress to process form submission. github
MVC provides aBindingResultto gather all of the binding errors and constraint voilations in the request. mvc
Inject it in the controller class. app
@Inject private BindingResult validationResult;
In the controller method, add@Validannotation on the methed parameters. jsp
@ValidateOnExecution(type = ExecutableType.NONE) public Response save(@Valid @BeanParam TaskForm form) { log.log(Level.INFO, "saving new task @{0}", form); if (validationResult.isFailed()) { AlertMessage alert = AlertMessage.danger("Validation voilations!"); validationResult.getAllViolations() .stream() .forEach((ConstraintViolation t) -> { alert.addError(t.getPropertyPath().toString(), "", t.getMessage()); }); models.put("errors", alert); return Response.status(BAD_REQUEST).entity("add.jspx").build(); } }
If the validation is failed, theisFailedmethod should returntrue. ide
You can iterate all voilations(validationResult.getAllViolations()) and gather the voilation details for each properties. ui
Then display the error messages in the JSP pages. spa
<c:if test="${not empty errors}"> <c:forEach items="${errors.errors}" var="error"> <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true"><![CDATA[×]]></span> </button> <p>${error.field}: ${error.message}</p> </div> </c:forEach> </c:if>
Like JAX-RS exception handling, you can handle exception viaExceptionMapperand display errors in the certain view. code
Create a customExceptionMapperand add annotation@Provider. orm
@Provider public class TaskNotFoundExceptionMapper implements ExceptionMapper<TaskNotFoundException>{ @Inject Logger log; @Inject Models models; @Override public Response toResponse(TaskNotFoundException exception) { log.log(Level.INFO, "handling exception : TaskNotFoundException"); models.put("error", exception.getMessage()); return Response.status(Response.Status.NOT_FOUND).entity("error.jspx").build(); } }
Different from JAX-RS, the entity value is the view that will be returned. In the error.jspx file, display theerrormodel via EL directly.
<div class="container"> <div class="page-header"> <h1>Psst...something was wrong!</h1> </div> <div class="row"> <div class="col-md-12"> <p class="text-danger">${error}</p> </div> </div> </div>
When theTaskNotFoundExceptionis caught, it will display the erorr like the following.
Clone the codes from my github.com account.
Open the mvc project in NetBeans IDE.