In series (4) and (5), we show how to bind data, and how to ensure the correctness of the data we get after binding data? This is what we are going to talk about in this article -> Data verification.
Here we use Hibernate-validator for verification. Hibernate-validator implements the JSR-303 verification framework to support annotation style verification. First, we need to download the required jar package at http://hibernate.org/validator/. Here we use 4.3.1.Final as a demonstration. After decompression, add the three packages hibernate-validator-4.3.1.Final.jar, jboss-logging-3.1.0.jar, validation-api-1.0.0.GA.jar to the project.
Configure the springservlet-config.xml file in the previous project, as follows:
<!-- Support for default annotation mapping --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean id="validator"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!--If not set, defaults to ValidationMessages.properties under classpath --> <property name="validationMessageSource" ref="validatemessageSource"/> </bean> <bean id="conversion-service" /> <bean id="validatemessageSource"> <property name="basename" value="classpath:validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>
The classpath:validatemessages in <property name="basename" value="classpath:validatemessages"/> is the file where the annotation verification message is located, and we need to add it in the resources folder.
Add a ValidateController.java content in the com.demo.web.controllers package as follows:
package com.demo.web.controllers;import java.security.NoSuchAlgorithmException;import javax.validation.Valid;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.ValidateModel;@Controller@RequestMapping(value = "/validate")public class ValidateController { @RequestMapping(value="/test", method = {RequestMethod.GET}) public String test(Model model){ if(!model.containsAttribute("contentModel")){ model.addAttribute("contentModel", new ValidateModel()); } return "validatetest"; } @RequestMapping(value="/test", method = {RequestMethod.POST}) public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{ //If there is a verification error, return to the form page if(result.hasErrors()) return test(model); return "validatesuccess"; } }@Valid @ModelAttribute("contentModel") ValidateModel validateModel @Valid means to verify after binding the data to @ModelAttribute("contentModel").
Add a ValidateModel.java content in the com.demo.web.models package as follows:
package com.demo.web.models;import org.hibernate.validator.constraints.Email;import org.hibernate.validator.constraints.NotEmpty;import org.hibernate.validator.constraints.Range;public class ValidateModel{ @NotEmpty(message="{name.not.empty}") private String name; @Range(min=0, max=150,message="{age.not.inrange}") private String age; @NotEmpty(message="{email.not.empty}") @Email(message="{email.not.correct}") private String email; public void setName(String name){ this.name=name; } public void setAge(String age){ this.age=age; } public void setEmail(String email){ this.email=email; } public String getName(){ return this.name; } public String getAge(){ return this.age; } public String getEmail(){ return this.email; } }Add the following content to the file where the annotation verification message is located, the validatemessages.properties file:
name.not.empty=/u540D/u79F0/u4E0D/u80FD/u4E3A/u7A7A/u3002age.not.inrange=/u5E74/u9F84/u8D85/u51FA/u8303/u56F4/u3002email.not.correct=/u90AE/u7BB1/u5730/u5740/u4E0D/u6B63/u786E/u3002email.not.empty=/u7535/u5B50/u90AE/u4E0D/u80FD/u60DF/u6050/u3002email.not.empty=/u7535/u5B50/u90AE/u4E0D/u80FD/u6050/u3002email.not.empty=/u7535/u5B50/u90AE/u4E0D/u80FD/u60DF/u6050/u3002
Among them, name.not.empty, etc. correspond to the xxx name in message=”xxx” in the ValidateModel.java file. The following content is entered in the ASCII encoding that is automatically converted in Chinese. Of course, you can also write xxx directly as prompt content without creating another validatemessages.properties file and adding it. However, this is incorrect, because if you hardcode it, you will not be able to internationalize it.
Add two views in the views folder, validatetest.jsp and validatesuccess.jsp, respectively:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <form:form modelAttribute="contentModel" method="post"> <form:errors path="*"></form:errors><br/> name:<form:input path="name" /><br/> <form:errors path="name"></form:errors><br/> age:<form:input path="age" /><br/> <form:errors path="age"></form:errors><br/> e-mail:<form:input path="age"></form:errors><br/> path="email" /><br/> <form:errors path="email"></form:errors><br/> <input type="submit" value="Submit" /> </form:form> </body></html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> Verification is successful! </body></html>
It is particularly important to point out that the name xxx after modelAttribute="xxx" in the validatetest.jsp view must be consistent with the name xxx in the corresponding @Valid @ModelAttribute("xxx"), otherwise the model data and error information will not be bound.
<form:errors path="name"></form:errors> will display error information for the corresponding attributes of the model. When path="*", error information for all attributes of the model is displayed.
Run the test:
Click to submit directly:
You can see the error message that the settings are correctly displayed.
Fill incorrect data to submit:
You can see that the error message that is still displayed correctly.
Fill in the correct data to submit:
You can see that the verification is successful.
The following are the main verification notes and instructions:
The data verification content ends here, code download: demo
For more information, please refer to the official document: http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.