Getting started wtih MVC(3)

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 similiar progress to process form submission.

  1. Gather user input form data.
  2. Convert form data to the target form bean. If there are some conversion failure, it is possbile to stop the progress and notify user.
  3. Bind the converted value to the form bean.
  4. Validate the form bean via Bean Validation. If there are some constraint voilations, it is possbile to stop the progress and notify user.
  5. Continue to process form.

MVC provides aBindingResultto gather all of the binding errors and constraint voilations in the request.

Handling form validation

Inject it in the controller class.

@Inject
private BindingResult validationResult;

In the controller method, add@Validannotation on the methed parameters.

@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.

You can iterate all voilations(validationResult.getAllViolations()) and gather the voilation details for each properties.

Then display the error messages in the JSP pages.

<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[&times;]]></span>
        </button>
        <p>${error.field}: ${error.message}</p>
    </div>
    </c:forEach>
</c:if>

Handling exception

Like JAX-RS exception handling, you can handle exception viaExceptionMapperand display errors in the certain view.

Create a customExceptionMapperand add annotation@Provider.

@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.

mvc error

Source codes

  1. Clone the codes from my github.com account.

    https://github.com/hantsy/ee8-sandbox/

  2. Open the mvc project in NetBeans IDE.

  3. Run it on Glassfish.
  4. After it is deployed and runging on Glassfish application server, navigate http://localhost:8080/ee8-mvc/mvc/tasks in browser.

转载于:https://my.oschina.net/hantsy/blog/661430

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值