This article has two points to note:
- This article only describes the code related to validation, if you are unfamiliar with other Springmvc, please learn it yourself first.
- This article verifies that the name in the book class has a length of 2 to 10,ISBN and must be 13 bits
First, add the validation jar package that needs to use the Hibrenate
Baidu Cloud Link: http://pan.baidu.com/s/1pJusKEv Password: k6u9
A test for the Pojo class book
PackageCom.elin4it.ssm.pojo;ImportOrg.hibernate.validator.constraints.NotEmpty;ImportSun.security.util.Length;ImportJavax.validation.constraints.Size;/** * Description:book * Author:elin Zhou * create:2015-07-03 21:43 * * Public class book { PrivateString name;PrivateString ISBN; PublicStringGETISBN() {returnISBN } Public void SETISBN(String ISBN) { This. ISBN = ISBN; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; }@Override PublicStringtoString() {return "book{"+"Isbn= '"+ ISBN +' \ '+", Name= '"+ name +' \ '+'} '; }}
Two JSP pages, one for displaying the form, and one for the successful display interface
addbook.jsp
<%@ taglib prefix="C" uri="Http://java.sun.com/jsp/jstl/core" %><%--Created by IntelliJ idea. User:elin Date: 7-3time: PM 3: one to change this template use File | Settings | File templates.--%> <%@ page contenttype="Text/html;charset=utf-8" language="java" %><html><head> <title></title></head><body> <form Action="<%=request.getcontextpath ()%>/book/addbookhandle" Method="POST">Title:<input type="text" name="name"><br>Isbn:<input type="text" name="ISBN"><br> <input type="Submit" value="Submit"><br> </form></body></html>
success.jsp
<%--Created by IntelliJ idea. User:elin Date: 7-3Time: PM 9: To Change this template use File | Settings | File templates.--%> <%@ page contenttype="Text/html;charset=utf-8" language="java" %><html><head> <title></title></head><body><H1>SUCCESS</H1></body></html>
- Configuring the bean for validation in the SPRINGMVC configuration file
The SPRINGMVC configuration file requires two steps to create a bean and then configure the
<!--validation--> <bean id= "validatorfactory" class=" Org.springframework.validation.beanvalidation.LocalValidatorFactoryBean "> < property name= "providerclass" value=" Org.hibernate.validator.HibernateValidator "/> < property name= "validationmessagesource" ref=" Messagesource "/> </Bean> <bean id= "messagesource" class=" Org.springframework.context.support.ReloadableResourceBundleMessageSource "> < property name="Basenames"> <list> <!--Verify the information configuration file, do not need some .properties--> <value>Classpath:com/elin4it/ssm/config/validationmessage</value> </list> </Property > <!--default encoding -- < property name="defaultencoding" value="Utf-8"/> <!--cache time - < property name="Cacheseconds" value="/>" </Bean>
Then you need to configure the Bean in Annotation-driven
<mvc:annotation-driven validator="validatorFactory"></mvc:annotation-driven>
- To add a validation prompt information file
A hint file is configured based on the path and file name that is written when the bean is configured, only the title and ISBN length are verified here.
book.name.notEmpty=书名不能为空book.isbn.size.error=ISBN必须为13位
- Adding validation rules to Pojo
Validation rules for attributes add annotations before the variable definition of the Pojo
So the Pojo specified position is modified as follows
@NotEmpty"{book.name.notEmpty}")private String name;@Size1313"{book.isbn.size.error}")private String isbn;
Where message is the key name defined in the previous hint message file
- Accept the validation results in the controller
Two points to take note of validation information
First: Add @validated annotations before the Pojo parameter name that is received when the form is submitted
Second: Add parameters of type Bindingresult in the parameter of the Controller method
by calling Bindingresult. HasErrors () You can get any errors generated
Bindingresult.getallerrors () Get all the objecterror types of errors
Objecterror.getdefaultmessage () Getting the wrong information
The controller verification method code is as follows
@RequestMapping ("/addbookhandle") PublicModelandviewAddbookhandel(@Validated book Book,bindingresult Bindingresult) {Modelandview Modelandview =NewModelandview ();if(Bindingresult.haserrors ()) {//Get all the errorslist<objecterror> errors = Bindingresult.getallerrors (); for(Objecterror objecterror:errors) {//Print error MessagesSystem. out. println (Objecterror.getdefaultmessage ()); } modelandview.addobject (book);//If an error occurs, the original page of the jumpModelandview.setviewname ("Book/addbook"); }Else{Modelandview.setviewname ("Success"); }returnModelandview;}
Sometimes, the properties to be validated are not immutable, sometimes only the titles need to be verified, sometimes only the ISBN is validated, so the validation rules need to be grouped.
Define several Java classes based on the number of groups to be divided, no inheriting classes or implementing interfaces, and no content is required in the class
Like creating ValidateType1 and ValidateType2 now.
Then define its group properties when defining the rule in the Pojo class, for example
@NotEmpty"{book.name.notEmpty}",groups = ValidationType1.class)private String name;@Size1313"{book.isbn.size.error}",groups = ValidationType2.class)private String isbn;
The validation rules that need to be executed are then added to the @validated annotations of the corresponding controller method, such as
publicaddUserHandle(@Validated(ValidationType1.class) User user,BindingResult bindingResult)
So in this method, only the title will be verified.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Springmvc using hibrenate validation for validation