How to solve the problems encountered by springmvc project using @ Valid+BindingResult
This article introduces the relevant knowledge of "how to solve the problems encountered in the use of @ Valid+BindingResult in springmvc projects". 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!
Step 1: introduce javax.validation and hibernate-validator javax.validation validation-api 2.0.1.Final org.hibernate hibernate-validator into pom.xml 6.0.16.Final
Previously, I only introduced javax verification, so that the system will not report an error. That is, the errors returned by bindingResult has always been 0. The check doesn't work.
Step 2: create a parameter bean class that requires verification
Classes to be introduced:
Import javax.validation.constraints.Min;import javax.validation.constraints.NotBlank;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;@Componentpublic class UserScheduleByManualBean implements Serializable {/ * / private static final long serialVersionUID = 8093326646402381469L; @ NotBlank (message = "the event cannot be empty") private String matchEventName / / event name @ NotBlank (message = "firing time cannot be empty") @ Pattern (regexp = "([0-9] {3} [1-9] | [0-9] {2} [1-9] [0-9] {1} | [0-9] {1-9] [0-9] {2} | [1-9] [0-9] {3}) 13578] | 1 [02])-(0 [1-9] | [12] [0-9] | 3 [01])) | ((0 [469] | 11)-(0 [1-9] | [12] [0-9] | 30)) | (02-(0 [1-9] | [1] [0-9] | 2 [0-8]) | (([0-9] {2}) (0 [48] | [2468] [048] | [13579] [26])) ]) | (0 [48] | [2468] [048] | [3579] [26]) 00))-02-29))\\ s ([0-1] [0-9] | 2 [0-3]): ([0-5] [0-9]): ([0-5] [0-9]) $" Message = "incorrect firing format") private String gunTime / / time of firing @ NotNull (message = "country ID cannot be empty") @ Min (value = 0ther message = "country ID data format error") private int dicCountryId; / / country ID @ NotBlank (message = "country name cannot be empty") private String countryName / / country name @ NotNull (message = "province ID cannot be empty") @ Min (value = 0century message = "province ID data format error") private int dicProvinceId; / / province ID @ NotBlank (message = "province name cannot be empty") private String provinceName / / Province name @ NotNull (message = "City ID cannot be empty") @ Min (value = 0recom message = "City ID data format error") private int dicCityId; / / City ID @ NotBlank (message = "City name cannot be empty") private String cityName; / / City name private String projectName / / Project name private String remarks; / / description can be empty private String bib; / / match number can be empty / / get and set method ignore} two problems must be paid attention to here
1: add the @ Component annotation to bean, and the spring configuration must scan this package, otherwise it will not take effect.
2: @ valid check with a lot of restrictions (attached below). The corresponding data type is not the same for the restriction comments that do not work. For example, the @ Pattern annotation can only be used on String types. I initially hoped that the properties of int would also be validated directly through the regularity. Result error: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type' java.lang.Integer'
3: you can have multiple comments
Step 3: write the controller class
First, let's create an BaseController abstract class with the BindingResult check method, and all other controller inherits this class to implement the check.
Introduced java classes:
Import org.springframework.validation.BindingResult; import javax.validation.Valid;public abstract class BaseController {/ * the verification result method that passes bean as a parameter * @ param bindingResult * @ return * / protected Map validate (BindingResult bindingResult) {Map ret = new HashMap (); boolean isTrue = true StringBuilder sb = new StringBuilder (""); if (bindingResult.hasErrors ()) {bindingResult.getAllErrors () .forEach (o-> {FieldError error = (FieldError) o; sb.append ("|" + error.getDefaultMessage ()); / / add error message}) IsTrue = false;} ret.put ("isTrue", isTrue); ret.put ("message", sb.toString ()); / / error message return ret;}}
Second, we create the controller class of the business, inheriting from BaseController.
@ Api (value = "TestController-API", description = "Test Operation Interface") @ Controller@RequestMapping ("testController/*") public class TestController extends BaseController {@ RequestMapping (value = "tstex", method = RequestMethod.POST, produces = "application/json" Charset=UTF-8 ") @ ApiOperation (value =" Test exception method ", notes =" Test exception method ") public @ ResponseBody String tstex (@ Valid @ RequestBody UserScheduleByManualBean userScheduleByManualBean, BindingResult bindingResult) {Map ret = new HashMap (); / / verify whether userScheduleByManualBean is legal Map validRet = validate (bindingResult) Boolean isTrue = (Boolean) validRet.get ("isTrue"); if (! isTrue) {/ / invalid parameter String erroMsg = (String) validRet.get ("message"); ret.put ("resultCode", "0001") Ret.put ("resultDesc", "parameter error" + erroMsg); return JsonUtil.gson_ObjectToJSON (ret);} ret.put ("resultCode", "0000"); ret.put ("resultDesc", "success"); return JsonUtil.gson_ObjectToJSON (ret);}}
Note here: @ Valid and @ RequestBody are positional, and must be preceded by @ Valid. BindingResult bindingResult is passed in as a parameter, then the parameter is verified by validate, and the uniform return result is set.
The result of running through swagger is as follows:
The attached restriction notes indicate that the sample @ Null restriction can only be null all @ Null (message= ") @ NotNull restrictions must not be null all @ NotNull (message=") @ AssertFalse restrictions must be false
@ AssertTrue limit must be true
The @ DecimalMax (value) limit must be a number not greater than the specified value
The @ DecimalMin (value) limit must be a number not less than the specified value
@ Digits (integer,fraction) limit must be a decimal, and the number of digits in the integer part cannot exceed integer, and the number of digits in the decimal part cannot exceed fraction
The @ Future restriction must be a future date
@ Max (value) limit must be a number not greater than the specified value int@Max (value=100,message= "") @ Min (value) limit must be a number not less than the specified value int@Min (value=100,message= "") @ Past limit must be a past date
The @ Pattern (value) restriction must conform to the specified regular expression String
@ Pattern (regexp= "", message= "")
@ Size (max,min) limit character length must be between min and max
@ NotEmpty verifies that the element value of the annotation is not null and is not empty (string length is not 0, collection size is not 0) String
@ NotEmpty (message = "")
@ NotBlank verifies 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, which only applies to strings and removes string spaces when comparing
@ NotBlank (message = "")
@ Email verifies that the element value of the annotation is Email, or you can specify a custom email format String through regular expressions and flag
This is the end of the content of "how to solve the problems encountered in the use of @ Valid+BindingResult in springmvc projects". 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!