In series (SpringMVC Learning Series (6) Data Verification) and (SpringMVC Learning Series (6) Data Verification) we showed how to bind data. After binding the data, how to ensure the correctness of the data we get? This is what we are going to talk about in this article —> Data validation.
Here we use Hibernate-validator for verification. Hibernate-validator implements the JSR-SpringMVC Learning Series (6) Data Verification0SpringMVC Learning Series (6) Data Verification verification framework and supports annotation-style verification. First we have to go to http://www.php.cn/ to download the required jar package. Here we use SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.Final as a demonstration. After decompression, hibernate-validator-SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification.Final.jar and jboss-logging-SpringMVC Learning Series (6) Data Verification.SpringMVC Learning Series (6) Data Verification The three packages .0.jar and validation-api-SpringMVC Learning Series (6) Data Verification.0.0.GA.jar are added to the project.
Configure the springservlet-config.xml file in the previous project as follows:
<!-- 默认的注解映射的支持 --> <annotation-driven></annotation-driven> <bean> <property></property> <!--不设置则默认为classpath下的 ValidationMessages.properties --> <property></property> </bean> <bean></bean> <bean> <property></property> <property></property> <property learning series data verificationspringmvc verification0></property> </bean>
whereproperty name="basename" value="classpath:validatemessages"/> in classpath:validatemessagesFor the file where the annotation verification message is located, we need to add it in the resources folder.
Add a ValidateController.java in the com.demo.web.controllers package with the following content:
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{ //如果有验证错误 返回到form页面 if(result.hasErrors()) return test(model); return "validatesuccess"; } }
Among them @Valid @ModelAttribute("contentModel") ValidateModel validateModel's @Valid means to validate after binding the data to @ModelAttribute("contentModel").
Add a ValidateModel.java in the com.demo.web.models package with the following content:
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=SpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification0,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; } }
Annotate the file where the verification message is located, which is validatemessages. Add the following content to the properties file:
name.not.empty=\uSpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification0D\u79F0\uSpringMVC Learning Series (6) Data VerificationE0D\u80FD\uSpringMVC Learning Series (6) Data VerificationESpringMVC Learning Series (6) Data VerificationA\u7A7A\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification age.not.inrange=\uSpringMVC Learning Series (6) Data VerificationE7SpringMVC Learning Series (6) Data Verification\u9F8SpringMVC Learning Series (6) Data Verification\u8D8SpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data VerificationFA\u8SpringMVC Learning Series (6) Data Verification0SpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data Verification6FSpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification email.not.correct=\u90AE\u7BBSpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data Verification7SpringMVC Learning Series (6) Data Verification0\uSpringMVC Learning Series (6) Data Verification7SpringMVC Learning Series (6) Data Verification0\uSpringMVC Learning Series (6) Data VerificationE0D\u6B6SpringMVC Learning Series (6) Data Verification\u786E\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification email.not.empty=\u7SpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data VerificationSpringMVC Learning Series (6) Data Verification\uSpringMVC Learning Series (6) Data VerificationBSpringMVC Learning Series (6) Data Verification0\u90AE\uSpringMVC Learning Series (6) Data VerificationEF6\uSpringMVC Learning Series (6) Data VerificationE0D\u80FD\u60DF\u60SpringMVC Learning Series (6) Data Verification0\uSpringMVC Learning Series (6) Data Verification00SpringMVC Learning Series (6) Data Verification
name.not.empty, etc. respectively correspond to the xxx name in message="xxx" in the ValidateModel.java file, and the following The content is the ASCII code that is automatically converted when inputting Chinese. Of course, you can also write xxx directly as the prompt content without creating another validatemessages.properties file and adding it, but this is incorrect because if it is hard-coded, there will be no The method has been internationalized.
Add two views, validatetest.jsp and validatesuccess.jsp, in the views folder. The contents are as follows:
nbsp;html PUBLIC "-//WSpringMVC Learning Series (6) Data VerificationC//DTD HTML SpringMVC Learning Series (6) Data Verification.0SpringMVC Learning Series (6) Data Verification Transitional//EN" "http://www.wSpringMVC Learning Series (6) Data Verification.org/TR/htmlSpringMVC Learning Series (6) Data Verification/loose.dtd"><meta><title>Insert title here</title> <form> <errors></errors><br><br> name:<input><br> <errors></errors><br> age:<input><br> <errors></errors><br> email:<input><br> <errors></errors><br> <input> </form>
nbsp;html PUBLIC "-//WSpringMVC Learning Series (6) Data VerificationC//DTD HTML SpringMVC Learning Series (6) Data Verification.0SpringMVC Learning Series (6) Data Verification Transitional//EN" "http://www.wSpringMVC Learning Series (6) Data Verification.org/TR/htmlSpringMVC Learning Series (6) Data Verification/loose.dtd"><meta><title>Insert title here</title> 验证成功!
It is particularly important to point out that in the validatetest.jsp view, form:form modelAttribute="contentModel" method="post">#modelAttribute="xxx"The name xxx following must be the same as Corresponding @Valid @ModelAttribute("xxx") The xxx names in are consistent, otherwise the model data and error information will not be bound.
form:errors path="name">form:errors>The error message corresponding to the attribute of the model will be displayed. When path="*", the error message of all attributes of the model will be displayed. error message.
Run the test:
## Click submit directly:
##You can see The error message for the setting is displayed correctly.
Fill in incorrect data and submit:
You can see that the set error message is still displayed correctly.
Fill in the correct data and submit:
The following are the main verification annotations and instructions:
Applicable data types |
Description |
|
Boolean, boolean |
Verify that the element value of the annotation is false |
|
@AssertTrue |
Boolean, boolean |
Verify that the element value of the annotation is true |
@DecimalMax(value=x) |
##BigDecimal, BigInteger, String, byte, short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. | Verify that the annotated element value is less than or equal to the value specified by @DecimalMax |
@DecimalMin(value=x) | ##BigDecimal, BigInteger, String, byte, short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.Verify that the annotated element value is less than or equal to the value specified by @DecimalMin | |
@Digits(integer=integer digits, fraction=decimal digits)
| BigDecimal, BigInteger, String, byte, short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.Verify the element value of the annotation The upper limit of the number of integers and decimal places | |
java.util .Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. |
Verify that the annotated element value (date type) is later than the current time | |
BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number. |
Verify that the element value of the annotation is less than or equal to the value specified by @Max | |
BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number. |
Verify that the element value of the annotation is greater than or equal to the value specified by @Min |
|
@NotNull |
##Any type | Verify that the annotated element value is not null |
@Null |
Any type | Validate the annotated element The value is null |
##@Past ##java.util.Date, java.util .Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. |
Verify that the annotated element value (date type) is earlier than the current time | |
##String. Additionally supported by HV: any sub-type of CharSequence. |
Verify that the annotated element value matches the specified regular expression |
|
String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence. |
Verify that the element value of the annotation is within the specified range of min and max (inclusive), such as character length and collection size |
|
Any non-primitive type (reference type) |
Verify the associated object. For example, if there is an order object in the account object, specify Validate order object |
##@NotEmpty |
CharSequence , | Collection, Map and Arrays |
Verify that the element value of the annotation is not null and not empty (the string length is not 0 and the collection size is not 0) |
@Range(min=minimum value, max=maximum value) |
##CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence , byte, short, int, long and the respective wrappers of the primitive types |
Verify that the element value of the annotation is between the minimum and maximum values |
@NotBlank |
##CharSequence | Verify that the element value of the annotation is not empty (not null, and the length is 0 after removing the first space). Unlike @NotEmpty, @NotBlank only applies to strings and will remove spaces from the strings during comparison |
@Length(min=lower limit, max=upper limit)
|
CharSequence | Verify that the element value length of the annotation is within the min and max intervals|
|

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function