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 Bean Validation in java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article introduces the knowledge of "how to use Bean Validation in java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Concept: Bean Validation in java is a specification for data validation.

Description: Hibernate Validator is a specific implementation of Bean Validation.

Example: using Hibernate Validator in springMVC

1) maven dependency: javax.validation validation-api 1.1.0.Final org.hibernate hibernate-validator 5.1.2.Final 2) JavaBean: import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank / * add comments to the attributes that need to be verified: * * 1) constraint provided by Bean Validation: * [@ Null] (the annotated element of https://my.oschina.net/u/561366) must be null * [@ NotNull ] (https://my.oschina.net/notnull) annotated elements must not be null * @ AssertTrue annotated elements must be true * [@ AssertFalse] (https://my.oschina.net/u/2430840) annotated elements must be false * @ Min (value) The annotated element must be a number Its value must be greater than or equal to the specified minimum value * @ Max (value) the annotated element must be a number, its value must be less than or equal to the specified maximum value * @ DecimalMin (value) the annotated element must be a number Its value must be greater than or equal to the specified minimum value * @ DecimalMax (value) the annotated element must be a number Its value must be less than or equal to the specified maximum value * @ Size (max=, min=) the size of the annotated element must be within the specified range * @ Digits (integer, fraction) the annotated element must be a number Its value must be within an acceptable range * @ Past the annotated element must be a past date * @ Future the annotated element must be a future date * @ Pattern (regex= Flag=) the annotated element must conform to the specified regular expression * * 2) Hibernate Validator-specific constraint: * @ NotBlank (message =) validation string is not null And the length must be greater than 0 * @ NotEmpty the annotated string or collection must not be empty * @ Email the annotated element must conform to the format of email * @ Length (min= Max=) the size of the annotated string must be within the specified range * @ Range (min=,max=,message=) the annotated element must be within the appropriate range * * / public class User {@ NotBlank (message= "name is null!") Private String name; @ NotNull (message = "age is null!") Private Integer age; private String email; private String address; / / getter and setter.. } 3) Controller: import javax.validation.Valid; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMethod RestController @ RequestMapping ("/ sys") public class UserController {/ * * 1. Add @ Valid annotation * 2 to the parameters that need to be verified. Add a parameter of type BindingResult to the method Used to encapsulate the result of the verification * / @ RequestMapping (value = "/ user/add", method = RequestMethod.POST) public String addUser (@ Valid @ RequestBody User req, BindingResult bindingResult) {if (bindingResult.hasErrors ()) {List allErrors = bindingResult.getAllErrors () List msgs = new ArrayList (); for (ObjectError objectError: allErrors) {String msg = objectError.getDefaultMessage (); msgs.add (msg) } String paramErrorMsg = StringUtils.join (msgs, "&"); return paramErrorMsg;} else {System.out.println ("do add user.") Return "success!" } 4) API test: address: http://localhost:8081/jxn-web/api/sys/user/add request type: Content-Type: application/json parameter: {"name": "" "age": null} = = > response content: age is null! & name is null! {"name": "," age ":"} = = > response content: age is null! & name is null! {"name": "jack", "age": "17"} = = > response content: success!

Common errors:

Error report: javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Integer. Analysis: because @ NotBlank modifies the properties of reference types such as Integer, Long, and so on, eg: @ NotBlank private Integer age; modifies that @ NotNull should be used to modify the properties of reference types. That's all for @ NotNull private Integer age;, "how to use Bean Validation in java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Servers

Wechat

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

12
Report