1. summary
In this article, we will focus on Spring in @Valid and @Validated The difference between annotations .
Verifying that user input is correct is a common feature in our applications .Spring Provides @Valid
and @Validated
Two annotations to implement the verification function , Let's talk about them in detail .
2. @Valid and @Validate annotation
stay Spring in , We use @Valid
Annotation for method level validation , It can also be used to mark member properties for validation .
however , This annotation does not support group validation .@Validated
Group verification is supported .
3. Example
Let's consider a way to use Spring Boot Development of a simple user registry . First , We only have name
and password
attribute :
public class UserAccount {
@NotNull
@Size(min = 4, max = 15)
private String password;
@NotBlank
private String name;
// standard constructors / setters / getters / toString
}
Next , Let's take a look at the controller . ad locum , We are going to use with @Valid
endorsed saveBasicInfo
Method to verify user input :
@RequestMapping(value = "/saveBasicInfo", method = RequestMethod.POST)
public String saveBasicInfo(
@Valid @ModelAttribute("useraccount") UserAccount useraccount,
BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "error";
}
return "success";
}
Now let's test this method :
@Test
public void givenSaveBasicInfo_whenCorrectInput`thenSuccess() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfo")
.accept(MediaType.TEXT_HTML)
.param("name", "test123")
.param("password", "pass"))
.andExpect(view().name("success"))
.andExpect(status().isOk())
.andDo(print());
}
After confirming that the test runs successfully , Now let's expand the functionality . The next logical step is to convert it into a multi-step registration form , Like most guides . First step , name
and password
remain unchanged . In the second step , We're going to get other information , for example age
and phone
. therefore , We will update the domain object with the following additional fields :
public class UserAccount {
@NotNull
@Size(min = 4, max = 15)
private String password;
@NotBlank
private String name;
@Min(value = 18, message = "Age should not be less than 18")
private int age;
@NotBlank
private String phone;
// standard constructors / setters / getters / toString
}
however , This time, , We'll notice that previous tests failed . It's because we didn't deliver Age
and Telephone
Field .
To support this behavior , Let's introduce @Validated
Comments .
Group verification
, It's just grouping fields , Verify separately , For example, we divide user information into two groups :BasicInfo
and AdvanceInfo
You can set up two empty interfaces :
public interface BasicInfo {
}
public interface AdvanceInfo {
}
The first step will have BasicInfo
Interface , The second step Will have AdvanceInfo
. Besides , We will update UserAccount
Class to use these tag interfaces , As shown below :
public class UserAccount {
@NotNull(groups = BasicInfo.class)
@Size(min = 4, max = 15, groups = BasicInfo.class)
private String password;
@NotBlank(groups = BasicInfo.class)
private String name;
@Min(value = 18, message = "Age should not be less than 18", groups = AdvanceInfo.class)
private int age;
@NotBlank(groups = AdvanceInfo.class)
private String phone;
// standard constructors / setters / getters / toString
}
in addition , We will now update the controller to use @Validated
Comment instead of @Valid
:
@RequestMapping(value = "/saveBasicInfoStep1", method = RequestMethod.POST)
public String saveBasicInfoStep1(
@Validated(BasicInfo.class)
@ModelAttribute("useraccount") UserAccount useraccount,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
return "success";
}
After the update , Run the test again , Now it can run successfully . Now? , We have to test this new method :
@Test
public void givenSaveBasicInfoStep1`whenCorrectInput`thenSuccess() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/saveBasicInfoStep1")
.accept(MediaType.TEXT_HTML)
.param("name", "test123")
.param("password", "pass"))
.andExpect(view().name("success"))
.andExpect(status().isOk())
.andDo(print());
}
And it worked !
Next , Let's see @Valid
It is essential to trigger nested property validation .
4. Use @Valid
Annotations mark nested objects
@Valid Can be used to nest objects . for example , In our current scenario , Let's create a UserAddress
object :
public class UserAddress {
@NotBlank
private String countryCode;
// standard constructors / setters / getters / toString
}
To ensure that this nested object is verified , We will use @Valid
Annotation decoration properties :
public class UserAccount {
//...
@Valid
@NotNull(groups = AdvanceInfo.class)
private UserAddress useraddress;
// standard constructors / setters / getters / toString
}
5. summary
@Valid
The verification of the whole object is guaranteed , But it's about validating the entire object , Problems arise when only partial validation is required . Now , have access to @Validated
Group verification .
Reference resources
author :Jadepeng
Source :jqpeng Technical notepad --http://www.cnblogs.com/xiaoqi
Your support is a great encouragement to bloggers , Thank you for your careful reading .
The copyright of this article belongs to the author , Welcome to reprint , However, this statement must be retained without the consent of the author , And in the article page obvious position gives the original link , Otherwise, the right to pursue legal responsibility is reserved .
Spring Medium @Valid and @Validated Note more related articles that you use correctly
- Spring Transaction operation in 、 annotation 、 as well as XML To configure
Business The full name of a transaction is a database transaction , Is the basic unit of database concurrency control , It's a set of operations , These operations are either not performed , Or both , An integral . For example, our money transfer service , Database transactions need to be processed . At least two will be involved in the transfer SQ ...
- stay spring Notes that are often ignored in @Primary
stay spring Using annotations in , Regular use @Autowired, The default is based on the type Type To automatically inject . But there are some special circumstances , For the same interface , There may be several different implementation classes , By default, only one of them will be adopted @Primary ...
- Spring in Bean Common notes on Management
stay Spring in , Mainly used for management bean There are four main categories of annotations :1. For creating objects .2. Used to inject values into an object's properties .3. Used to change the scope of action .4. Used to define the life cycle . These are often encountered in development , It can also be said that we meet every day . among ...
- Spring Based on AOP Of @AspectJ Annotate examples
@AspectJ As by Java 5 Annotated ordinary Java class , It refers to a statement aspects A style of . Through your architecture based XML The configuration file contains the following elements ,@AspectJ Support is available ...
- Spring Notes on declarative transactions in @Transactional Summary of the parameters of (REQUIRED and REQUIRES_NEW The rollback problem with the main method )
One . The spread of transactions 1. Introduce When a transaction method is called by another transaction method , You must specify how transactions should propagate . for example : Method may continue to run in an existing transaction , It's also possible to start a new business , And run... In your own transaction .2. attribute The dissemination of a transaction can be carried out by ...
- In the use of spring Medium ContextConfiguration、test Error in annotation
error : Appears when using test annotations ContextConfiguration Notes and test Annotation can't properly import the compilation exception used by package , Pictured : terms of settlement : take pom.xml The following dependency management in the file Medium <scope> ...
- spring in xml Configuration methods and annotations annoation The way ( Include @autowired and @resource) The difference between
xml Configuration in file itemSqlParameterSourceProvider Yes. : <bean id="billDbWriter" class="com.aa. ...
- Spring Medium @response and @request annotation
@response The format returned by the annotation object is json Text @requestBody take json Object to the corresponding java class
- spring Use in @PostConstruct and @PreConstruct annotation
1.@PostConstruct explain By @PostConstruct The decorated method will be loaded on the server Servlet Run when , And will only be called by the server once , Be similar to Serclet Of inti() Method . By @PostCo ...
- spring Use... Based on annotations in AOP
The content of this article is :spring How to use annotations in aspect oriented programming , And how to use custom annotations . A scene Such as user login , Before each request is initiated, whether the user logs in or not will be judged , If every request is judged once , That's a lot to do over and over again , As long as there is ...
Random recommendation
- warensoft unity3d Update instructions
warensoft unity3d Component's Alpha The version has been released for nearly a year , Many netizens sent improved Email, Thank you for your support . Warensoft Unity3D Components will continue to update , The functions to be improved are as follows : 1. ...
- Lethal thunder dog ---node.js---1node Download and install
node There are currently two websites , One is in English , One is in Chinese ,, The one on the left is the long-term version , On the right is the latest version , You can see clearly below node The update speed of English website is much faster than that of Chinese website The version we're testing is windo ...
- WPF Medium Style( style , style )( turn )
stay WPF We can use Style To set some property values of the control , And make the setting affect all the controls in the specified range or one of the controls specified , For example, we want to keep all the buttons in the window in a certain style , So we can set up a Style, and ...
- Linux Several types of files
Several types of files : 1. Ordinary documents Ordinary documents are documents in the general sense , They are stored on the system disk as data , You can randomly access the contents of the file .Linux The files in the system are byte oriented , writing The contents of the file are stored and accessed in bytes ...
- Microsoft position internal recommendation -Software Development Engineer II
Microsoft recently Open Position : Job Title:Software Development EngineerII Division: Server & Tools Business - Comme ...
- 1515 jump - Wikioi
Title Description Description Cults like to jump in all kinds of spaces . Now? , The cult has come to a two-dimensional plane . In this plane , If the cult jumps to (x,y), Then he can choose to jump below next 4 A little bit :(x-1,y), (x+1,y ...
- HDU_1401—— Synchronous bidirectional BFS, Octal bit operation compression ,map Deposit hash
This is a little faster than step by step , A little bit more memory Problem Description Solitaire is a game played on a chessboard 8x8. The rows an ...
- swift location Convert the city name according to the longitude and latitude of the location
I haven't written essays for a long time Recently, the project is a little tight Working overtime every day National Day I haven't had a day off My baby All right. No complaints After all, it's no use I make complaints about Tucao's writing on that day
- bash The working characteristics and using methods of
bash The return value of the command execution status and the content involved in the command expansion and its examples are shown ! Script execution and debugging 1. Absolute path execution , The file is required to have execution authority 2. With sh Command execution , Do not require the file to have Execution Authority 3.. Add a space or source Command execution ...
- mac On adb command not found
The first kind of report is wrong ( It comes with mac Command line ) bash: adb: command not found 1.vim ~/.bash_profile , If .bash_profile non-existent , First touch ~/. ...