Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use @ Valid,@Validated and @ PathVariable in Java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to use @ Valid,@Validated and @ PathVariable in Java". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use @ Valid,@Validated and @ PathVariable in Java" can help you solve the problem.

@ Valid and @ Validated@Valid and @ Validated comparison

Similarities:

@ Valid annotations and @ Validated annotations are both annotations that enable the check function.

Differences:

@ Valid annotation: can be used on methods, constructors, method parameters, and member properties

@ Validated comment: can be used on types, methods, and method parameters. But it cannot be used on member properties.

The @ Validated annotation is a further encapsulation of Spring based on the @ Valid annotation and provides advanced features such as grouping and grouping order

Use in different locations:

@ Valid Advanced use @ Valid Cascade check

Cascade check: also known as nested detection. Nesting is that one entity class contains another entity class.

@ Valid and can be used on fields of member properties, so @ Valid can provide cascading checks

Example:

@ Datapublic class Hair {@ NotBlank (message = "hair length must be submitted!") Private Double length; @ NotBlank (message = "hair color must be submitted!") Private String color;} @ Datapublic class Person {@ NotBlank (message = "user name must be submitted!") @ Size (min=2, max=8) private String userName; / / add @ Valid annotation to achieve nested detection @ Valid @ NotEmpty (message = "users want hair!") Private List hairs;} @ PostMapping ("/ person") public Result addPerson (@ Valid @ RequestBody Person person) {return Result.buildSuccess (person);}

Just add @ Valid and @ Validated annotations before the method parameters, and do not validate the nested entity classes. To validate a nested entity class, you need to add the @ Valid annotation to the nested entity class attribute

@ Validated Advanced use @ Validated packet check

Packet check:

Enable verification for the specified group, which can be used in different business scenarios

The grouping check is provided by value in the @ Validated annotation

Groups:

@ Datapublic class PersonGroup {public interface AddGroup {} public interface UpdateGroup {} / @ Validated Note the value method specifies @ NotBlank when grouping UpdateGroup.class (message = "user ID must be submitted!" , groups = UpdateGroup.class) private String id; / / @ Validated annotate the value method to specify @ NotBlank when grouping AddGroup.class or grouping UpdateGroup.class (message = "the user's name must be submitted!" , groups = {AddGroup.class, UpdateGroup.class}) private String name; / / @ Validated Note value method does not specify @ Range when grouping is specified (min = 1, max = 200, message = "user's age must be submitted!") Private int age;}

Grouping method groups in JSR 303 check annotations

Example:

Enable packet verification: enable verification for the specified packet through the value method annotated by @ Validated

@ RestController@RequestMapping ("/ person") public class PersonGroupController {/ / check @ GetMapping ("/ person") public Result getPerson (@ Validated @ RequestBody PersonGroup person) {return Result.buildSuccess (person) } / / specify AddGroup packet check @ PostMapping ("/ person") public Result addPerson (@ Validated (value = PersonGroup.AddGroup.class) @ RequestBody PersonGroup person) {return Result.buildSuccess (person) } / / specify UpdateGroup packet check @ PutMapping ("/ person") public Result updatePerson (@ Validated (value = PersonGroup.updateGroup.class) @ RequestBody PersonGroup person) {return Result.buildSuccess (person);}}

The check method adds the value of groups to specify the grouping, and only when you specify this grouping with the value of the value of @ Validated annotations, the function of checking data for annotations is turned on in a meeting.

@ Validated packet check order

By default, the constraints between groups are unordered, but in some special cases there may be a certain order of checks between groups.

For example, the constraint check of the second group needs to rely on the steady state of the first group. In this case, the constraint check between the groups must be in order.

The grouping check order is achieved by using @ GroupSequence annotations

Example:

@ Datapublic class UserGroupSequence {public interface FirstGroup {} public interface SecondGroup {} / use GroupSequence to define the packet verification order: verify @ GroupSequence ({FirstGroup.class, SecondGroup.class}) public interface Group {} @ NotEmpty according to the FirstGroup,SecondGroup grouping order (message = "user ID must be submitted!" , group = FirstGroup.class) private String userId; @ NotEmpty (message = "user name must be submitted!" , group = FirstGroup.class) @ Size (min = 2, max = 8, message = "the length of user name is between 2 and 8", goup = Second.class) private String userName } @ RestController@RequestMapping ("/ user") public class UserGroupSequenceController {/ / the value of @ Validated annotation value in the method here is Group.class @ PostMapping ("/ user") public Result addGroup (@ Validated (value = Group.class) @ RequestBody UserGroupSequence user) {return Result.buildSuccess (user);}}

After the @ GroupSequence annotation is used to specify the packet check order, the constraint check of the second group will not be carried out after the constraint check of the first group does not pass.

@ Validated non-entity class check

Add @ Validated annotation to the non-entity class to verify the non-entity class

@ Validatedpublic class AnnotationController {@ GetMapping ("/ person") public Result getAge (@ Range (min = 2, max = 8, message = "aged between 3 and 8!") @ RequestParam int age) {return Result.buildSuccess (age);}}

Add a global unified exception handling method to GlobalExceptionHandler:

@ ExceptionHandler (ConstraintViolationException.class) @ ResponseBodypublic Result resolveConstraintViolationException (ConstraintVilationException exception) {Set [] groups () default {}; Class

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report