Detailed SPRINGMVC Learning Series (6) Data validation _java

Source: Internet
Author: User
Tags jboss

In series (4), (5) We showed how to bind the data, how to ensure the correctness of the data we obtained after binding the data? This is what we are going to say in this article-> data validation.

Here we use Hibernate-validator to verify, Hibernate-validator implement the JSR-303 validation framework to support the annotation style validation. First we have to http://hibernate.org/validator/download the required jar package, here to 4.3.1.Final as a demo, decompression after the Hibernate-validator-4.3.1.final.jar, Jboss-logging-3.1.0.jar, Validation-api-1.0.0.ga.jar These three packages are added to the project.

Configure the Springservlet-config.xml files in the previous project, as follows:

 <!--default annotation mapping support--> <mvc:annotation-driven validator= "Validator" conversion-s Ervice= "Conversion-service"/> <bean id= "Validator" Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean "> <property name=" Providerclass " Value= "Org.hibernate.validator.HibernateValidator"/> <!--is not set, the default is validationmessages.properties under Classpath- -> <property name= "Validationmessagesource" ref= "Validatemessagesource"/> </bean> <bean id= "Conv Ersion-service "class=" Org.springframework.format.support.FormattingConversionServiceFactoryBean "/> <bean Id= "Validatemessagesource" class= "Org.springframework.context.support.ReloadableResourceBundleMessageSource" > <property name= "basename" value= "classpath:validatemessages"/> <property name= "Fileencodings" Valu E= "Utf-8"/> <property name= "cacheseconds" value= "/>" </bean> 

Where Classpath:validatemessages in the <property name= "basename" value= "/>" Classpath:validatemessages is the file that contains the annotation validation message, We need to add it under the Resources folder.

Add a Validatecontroller.java content to 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", met Hod = {Requestmethod.get}) public String test (model model) {if (!model.containsattribute ("Contentmodel")) {MoD
    El.addattribute ("Contentmodel", New Validatemodel ());
  Return to "Validatetest"; @RequestMapping (value= "/test", method = {requestmethod.post}) public String test (model model, @Valid @ModelAttrib Ute ("Contentmodel") Validatemodel Validatemodel, BindingresuLt result) throws nosuchalgorithmexception{//If a validation error is returned to the form page if (result.haserrors ()) return test (mode
    L);   
  return "Validatesuccess";

 }
  
}

Where the @valid meaning of the @valid @ModelAttribute ("Contentmodel") Validatemodel Validatemodel is to bind the data to @modelattribute (" Contentmodel ") is validated.

Add a Validatemodel.java content to 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 in the file, Validatemessages.properties file, where the note validation message is located:

name.not.empty=\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a\u3002
age.not.inrange=\u5e74\u9f84\u8d85\u51fa\u8303\ u56f4\u3002
email.not.correct=\u90ae\u7bb1\u5730\u5740\u4e0d\u6b63\u786e\u3002
email.not.empty=\u7535\ u5b50\u90ae\u4ef6\u4e0d\u80fd\u60df\u6050\u3002

Name.not.empty and so on, respectively, corresponding to the Validatemodel.java file in the message= "xxx" in the name of XXX, the following is in the input of Chinese is automatic conversion of ASCII encoding, of course, you can also directly write XXX as a hint content, Instead of building another validatemessages.properties file to add, this is not the correct approach, because so hard coded words there is no way to internationalize.

Add the validatetest.jsp and validatesuccess.jsp two views in the View folder, as follows:

<%@ 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 PR efix= "Form" uri= "Http://www.springframework.org/tags/form"%>  
<%@ 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" >
 
 

In particular, the <form:form modelattribute= "Contentmodel" method= "POST" > modelattribute= "xxx" in the validatetest.jsp view are highlighted The name xxx that follows must be the same as the xxx name in the corresponding @valid @ModelAttribute ("xxx"), otherwise the model data and error information are not bound.

<form:errors path= "name" ></form:errors> displays error messages for the corresponding properties of the model, and displays error messages for all properties of the model when path= "*".

To run the test:

Direct Click Submit:

You can see the error message that the settings are displayed correctly.

Fill in the Error data submission:

You can see the error message that still displays the settings correctly.

Fill in the correct data submission:

You can see that the validation was successful.

The following are the key validation notes and instructions:

The content of the data verification end, the Code downloads: Demo

For more information, please refer to the official documentation: http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.