10.5.2 Procedures for using Bean Validation from CDI

This subsection describes procedures for using Bean Validation from CDI.

Organization of this subsection
(1) Procedure required before using CDI
(2) Example of implementation

(1) Procedure required before using CDI

To perform the validation processing using Bean Validation with CDI:

  1. Use the @Inject annotation in the user application class to inject ValidatorFactory.
    Example: @Inject private ValidatorFactory validatorFactory
  2. To obtain the Validator object, invoke the validatorFactory.getValidator() of the user application from Bean Validation.
  3. Finally, invoke the validator.validate() method from the user application, and pass the Bean class to be validated.

(2) Example of implementation

The following is an example of implementation using Bean Validation from CDI.

The first example shows an implementation of the servlet that registers the information for which validation is required.

public class EmployeeServBv extends HttpServlet{
@Inject private ValidatorFactory validatorFactory;
@Inject BV_CDI bean;

 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException{
 Validator validator = validatorFactory.getValidator();
  validator.validate(bean);
 }
}

In this example, the Bean Validation annotation is applied in the BV_CDI bean.

The next example shows an implementation of the validation definition for the Bean that stores the data to be validated.

import javax.validation.constraints.NotNull;
public class BV_CDI{
   @NotNull
   private String name;
   public String getName(){
       return name;
   }
   public void setName(String name){
       this.name = name;
   }
}