Are you using the @ valid and @ validated annotations correctly in spring

JadePeng 2021-01-14 18:36:25
using valid validated annotations correctly


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 .

版权声明
本文为[JadePeng]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210114183551196k.html

  1. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  2. Learn about RPC, why RPC was born, and what's the difference between RPC and HTTP?
  3. Learn java base conversion supplementary learning
  4. JDBC测试连接数据库
  5. JDBC test connection database
  6. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  7. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  8. 安卓开发和java开发有什么区别!2021年BATJ30套大厂Android经典高频面试题,面试必问
  9. Spring Security OAuth2.0認證授權四:分散式系統認證授權
  10. What's the difference between Android development and java development! 2021 batj30 Android classic high frequency interview questions
  11. Spring security oauth2.0 authentication and authorization 4: distributed system authentication and authorization
  12. Java微服务 vs Go微服务,究竟谁更强!?
  13. 大厂面试官竟然这么爱问Kafka,一连八个Kafka问题把我问蒙了?
  14. Who is stronger, Java microservice vs go microservice!?
  15. Java微服务 vs Go微服务,究竟谁更强!?
  16. The interviewers of big factories love to ask Kafka so much. I'm blinded by eight Kafka questions in a row?
  17. Who is stronger, Java microservice vs go microservice!?
  18. springboot异常处理之404
  19. Spring boot exception handling 404
  20. Spring Boot Security 国际化 多语言 i18n 趟过巨坑
  21. springboot异常处理之404
  22. Spring boot security international multilingual I18N
  23. Spring boot exception handling 404
  24. Netty系列化之Google Protobuf编解码
  25. Netty之编解码
  26. Java编解码
  27. Netty解码器
  28. Netty与TCP粘包拆包
  29. Netty开发入门
  30. Java集合遍历时遇到的坑
  31. Spring IOC 源码解析(下)
  32. Spring IoC源码解析(上)
  33. Google protobuf codec of netty serialization
  34. Encoding and decoding of netty
  35. Java codec
  36. Netty decoder
  37. Netty and TCP packet sticking and unpacking
  38. Introduction to netty development
  39. Problems encountered in Java collection traversal
  40. Spring IOC source code analysis (2)
  41. Spring IOC source code analysis (Part one)
  42. 半小时用Spring Boot注解实现Redis分布式锁
  43. Implementing redis distributed lock with spring boot annotation in half an hour
  44. What should we do if we can't get tickets for Spring Festival transportation? You can solve this problem by using these ticket grabbing apps!
  45. 百度智能(文本识别),API传图OC代码与SDK使用
  46. springboot源码解析-管中窥豹系列之aware(六)
  47. Baidu intelligent (text recognition), API map, OC code and SDK
  48. Spring boot source code analysis
  49. springboot源码解析-管中窥豹系列之aware(六)
  50. 百度智能(文本识别),API传图OC代码与SDK使用
  51. Spring boot source code analysis
  52. Baidu intelligent (text recognition), API map, OC code and SDK
  53. Java学习笔记
  54. Java learning notes
  55. Sentry(v20.12.1) K8S 雲原生架構探索, SENTRY FOR JAVASCRIPT 手動捕獲事件基本用法
  56. 我的程式設計師之路:自學Java篇
  57. SpringBoot專案,如何優雅的把介面引數中的空白值替換為null值?
  58. Sentry (v20.12.1) k8s cloud native architecture exploration, sentry for JavaScript manual capture event basic usage
  59. My way of programmer: self study java
  60. Spring boot project, how to gracefully replace the blank value in the interface argument with null value?