跳至主要内容

Getting started with Java EE 8 MVC(3)-Exception Handling and form validation

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 a BindingResult to 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 @Valid annotation 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, the isFailed method should return true.
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 via ExceptionMapper and display errors in the certain view.
Create a custom ExceptionMapper and 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 the error model 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 the TaskNotFoundException is 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.

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =...

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert...

AngularJS CakePHP Sample codes

Introduction This sample is a Blog application which has the same features with the official CakePHP Blog tutorial, the difference is AngularJS was used as frontend solution, and CakePHP was only use for building backend RESR API. Technologies AngularJS   is a popular JS framework in these days, brought by Google. In this example application, AngularJS and Bootstrap are used to implement the frontend pages. CakePHP   is one of the most popular PHP frameworks in the world. CakePHP is used as the backend REST API producer. MySQL   is used as the database in this sample application. A PHP runtime environment is also required, I was using   WAMP   under Windows system. Post links I assume you have some experience of PHP and CakePHP before, and know well about Apache server. Else you could read the official PHP introduction( php.net ) and browse the official CakePHP Blog tutorial to have basic knowledge about CakePHP. In these posts, I tried to ...