Section V: data verification

Keywords: Spring MVC

1, Data verification

Data verification is involved in the project. If only front-end verification is unsafe, we can bypass the front-end verification, and the back-end verification must be added to important data;

1. Through the program, each data is taken out and verified. If it fails, go directly to the add page and prompt it to fill in again; (not recommended)

2. Spring MVC: JSR303 can be used for data verification;

 

2, How to verify

  1,JSR 303 

JSR 303 is a standard framework provided by Java for Bean data validity verification, which has been included in Java EE 6.0.

JSR 303 (Java Specification Requests means Java specification proposal) was passed in   Bean   Attribute is marked with annotations similar to @ NotNull, @ Max and other standards to specify the verification rules, and the bean is verified through the standard verification interface:

    

2. Hibernate Validator extension annotation

    Hibernate Validator   It is a reference implementation of JSR 303. In addition to supporting all standard verification annotations, it also supports the following extension annotations:

    

3. Spring MVC data verification

Spring 4.0 has its own independent data verification framework and supports the verification framework of JSR 303 standard;

During data binding, spring can call the verification framework to complete data verification at the same time. stay   Spring MVC   In, data verification can be directly carried out by annotation driven method;

Spring's LocalValidatorFactroyBean implements both the Validator interface of spring and the Validator interface of JSR 303. As long as a localvalidator factorybean is defined in the spring container, it can be injected into the Bean that needs data verification;

  Spring   JSR303 is not provided by itself   Therefore, JSR303 must be implemented   jar of implementer   Put the package under the classpath;

  <mvc:annotation-driven />   A LocalValidatorFactoryBean will be assembled by default and marked on the input parameters of the processing method  @ Valid   Annotation enables Spring MVC to perform data verification after data binding;

Mark @ Valid in front of the form / command object annotated with JSR303 annotation. After binding the request parameters to the input parameter object, the Spring MVC framework will call the verification framework to perform verification according to the verification rules declared by the annotation;

 

3, Realize data verification

1. Use JSR 303 verification standard

2. Join the hibernate validator verification framework

3. Add < MVC: annotation driven / > in spring MVC configuration file

4. You need to add the corresponding verification annotation on the bean attribute

5. Add @ Valid annotation in front of the target method bean type

4, Experimental code

1. Add dependency

Maven mode:

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
                <version>5.2.4.Final</version>
            </dependency>

 

jar package method:

hibernate-validator-5.0.0.CR2.jar
hibernate-validator-annotation-processor-5.0.0.CR2.jar
classmate-0.8.0.jar
jboss-logging-3.1.1.GA.jar
validation-api-1.1.0.CR1.jar

 

Note: Tomcat 7.0 is recommended. el expressions above Tomcat 7.0 are more powerful;

2. Add verification annotation to the verification attribute

public class Employee {

    private Integer id;
    @NotBlank
    @NotEmpty
    @Length(min = 6, max = 10, message = "Name exceeds length limit")
    private String lastName;

    @NotBlank
    @Email
    @Length(max = 15, message = "Email exceeds length limit")
    private String email;

    private Integer gender;

    //You can specify the date format of page submission
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @Past     //It must be a past time
    //@Future //Must be a future time
    private Date birth;

    //Hypothetical page, in order to display the salary 10000 submitted for convenience.98,---> ¥10,000.98
    @NumberFormat(pattern="#,###,###.##")
    private Double salary;
    private Department department;
}

 

3. When spring MVC encapsulates objects, tell spring MVC that this JavaBean needs verification

    /**
     * Save employee
     * Add @ Valid annotation. If the verification fails, an error will be reported.
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    public String addEmp(@Valid Employee employee) {
        System.out.println("employee = " + employee);
        return "success";
    }

 

4. How to know the verification results?

The JavaBean to be verified is followed by a BindingResult, which encapsulates the verification result of the previous Bean and cannot interval any parameters.

    /**
     * Save employee
     * Add @ Valid annotation. If the verification fails, an error will be reported.
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    public String addEmp(@Valid Employee employee, BindingResult result) {
        System.out.println("employee = " + employee);
        //Is there a verification error
        if (result.hasErrors()) {
            System.out.println("There are verification errors!!!");
            return "add";
        } else {
            //employeeDao.save(employee);
            System.out.println("Saved successfully!");
            return "success";
        }
    }

 

Decide how to operate according to different verification results

 

5, Display of error messages

1. Error information

public interface BindingResult extends Errors

  

Spring MVC saves the verification results by signing the processing method: the verification results of the previous form / command object are saved to the subsequent input parameters. The input parameters for saving the verification results must be of BindingResult or Errors type. Both classes are located in the org.springframework.validation package;

The Bean object to be verified and its binding result object or error object appear in pairs, and other input parameters are not allowed to be declared between them;

The Errors interface provides methods to obtain error information, such as getErrorCount() or getFieldErrors(String field)

BindingResult extends the Errors interface

  

 

2. Use the form label to echo the error results

Spring MVC not only saves the verification results of the form / command object to the corresponding BindingResult or Errors object, but also saves all verification results to the "implicit model";

Even if there is no result input parameter corresponding to the form / command object in the signature of the processing method, the verification result will be saved in the "hidden object";

All data in the implicit model will eventually be exposed to the JSP view object through the attribute list of HttpServletRequest, so the error information can be obtained in JSP

The error message can be displayed on the JSP page through < form: errors path = "userName" >

Use the < form: errors > tag to display an error prompt for this attribute:

<form:errors path="attribute"/>

Example:

Display all error messages on the form page:

<!-- Show all error messages -->
<form:errors path="*"/>

  

Display an error message for a form field:

<form:errors  path="lastName"/>  

  

Display the prompt of verification:

<form:form action="${ctx}/emp" modelAttribute="employee" method="POST">
    lastName: <form:input path="lastName" /> <form:errors path="lastName"/> <br/>
    email: <form:input path="email" /> <form:errors path="email"/><br/>
    gender: <br>
    male <form:radiobutton path="gender" value="1"/><br/>
    female <form:radiobutton path="gender" value="0" /><br/>
    birth: <form:input path="birth" /> <form:errors path="birth"/><br/>
    salary: <form:input path="salary" /><br/>
    dept:
    <form:select path="department.id" items="${depts}" itemLabel="departmentName" itemValue="id"></form:select>
    <br>
    <input type="submit" value="preservation">
</form:form>

 

3. Write back the verification information

BindingResult encapsulates the error information of type conversion and formatting. You can put the error information in the request field and bring it back to the page.

Example:

    /**
     * Save employee
     * Add @ Valid annotation. If the verification fails, an error will be reported.
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    public String addEmp(@Valid Employee employee, BindingResult result, Model model) {
        System.out.println("employee = " + employee);
        Map<String, Object> errorsMap = new HashMap<>();
        //Is there a verification error
        if (result.hasErrors()) {
            System.out.println("There are verification errors!!!");
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("Error message prompt:" + fieldError.getDefaultMessage()); //error message
                System.out.println("The wrong fields are:" + fieldError.getField());          //Error field
                System.out.println(fieldError);
                errorsMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            model.addAttribute("errorInfo", errorsMap);
            return "add";
        } else {
            //employeeDao.save(employee);
            System.out.println("Saved successfully!");
            return "success";
        }
    }

 

5, Internationalization of prompt messages

 

Vi

Posted by Calver on Thu, 02 Dec 2021 11:09:52 -0800