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

What are the ways to use BindingResult

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

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the methods of using BindingResult". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it slowly to study and learn "what are the methods of using BindingResult" together!

BindingResult Summary and Notes

Remember a simple and useful API: BindingResult

BindingResult is very simple to use, generally used in controller

Function: Used to check the parameters passed through the front end, eliminating a lot of logical judgment operations

Related Checkout API Empty Check

@NotEmpty: used on collection classes; cannot be null, and the length must be greater than 0

@NotBlank: used on String; can only be used on String, cannot be null, and after calling trim(), the length must be greater than 0

@NotNull: Used on base types; cannot be null, but can be empty.

length check

@Size(min=,max=): Verify that the length of the object (Array,Collection,Map,String) is within the given range. Do not misuse the exception type, such as @size is not available on int

@Length(min=, max=): only applicable to String type

Booelan Check

@AssertTrue: Verify Boolean object is true

@AssertFalse: Verify Boolean object is false

date checking

@Past: Verify that Date and Calendar objects are before the current time

@Future: Verify that Date and Calendar objects are after the current time

@Pattern: Verify that String objects conform to the rules of regular expressions

other verification

@Vaild recursive validation, used for objects, arrays and collections, will check the elements of the object, the elements of the array one by one

@Email is used to verify whether a string is a valid right-click address, empty string or null is verified

@URL(protocol=,host=,port=,regexp=,flags=) is used to verify whether a string is a valid URL

numeric check

Recommended on Stirng,Integer type, not recommended on int type, because form value "" cannot be converted to int, but can be converted to Stirng as "",Integer null

@Min: Verify that Number and String objects are equal to or greater than the specified value

@Max: Verify that Number and String objects are less than or equal to the specified value

@DecimalMax: The annotated value must be no greater than the maximum value specified in the constraint. The parameter to this constraint is a string representation of the maximum value defined by BigDecimal. fractional existence precision

@DecimalMin: The annotated value must not be less than the minimum value specified in the constraint. The argument to this constraint is a string representation of the minimum value defined by BigDecimal. decimal existence precision

@Digits: Verify that the composition of Number and String is legal

@Digits(integer=,fraction=): Verify that the string is a number in the specified format, interger specifies integer precision, fraction specifies fractional precision.

Problems encountered in project use

At first, the parameter passed in is not modified with @Validated. As a result, the binding does not work. The parameter verification fails. Add this comment to take effect.

So BingdingResult is to be used with @Validated.

The following are used in the project:

In controller:

@ApiOperation("Add Corner Color")@RequestMapping(value = "/create", method = RequestMethod.POST)@ResponseBodypublic CommonResult create(@Validated @RequestBody UmsRole role, BindingResult bindingResult ) { int count = roleService.create(role); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();}

In the domain:

import io.swagger.annotations.ApiModelProperty;import javax.validation.constraints.NotEmpty;import java.io.Serializable;import java.util.Date;@Datapublic class UmsRole implements Serializable { private Long id; @ApiModelProperty(value = "Name") @NotEmpty(message = "name cannot be empty! ") private String name; @ApiModelProperty(value = "Description") @NotEmpty(message = "Description cannot be empty! ") private String description; @ApiModelProperty(value = "Number of background users") private Integer adminCount; @ApiModelProperty(value = "Created on") private Date createTime; @ApiModelProperty(value = "Enabled Status: 0-> Disabled;1-> Enabled") private Integer status; private Integer sort; private static final long serialVersionUID = 1L;

Call the interface to return the effect:

Parameters:

{

"name":"test"

}

Return value:

{

"code": 404,

"message": "Description cannot be empty! ",

"data": null

}

Attention!

1.@ Validated and BindingResult need to be adjacent, otherwise the variable result cannot accept error messages

console output

Field error in object 'entity' on field 'variable': rejected value [null]; codes [NotNull.entity. variable,NotNull. variable,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes

2. If @Validated is used, BeanValidate will also throw an exception instead of wrapping it in BindingResult

Summary:

Using BindingResult eliminates most of the checks in the code block

BindingResult principle of action

controller code

@RequestMapping("") public String index(@Valid User user , BindingResult bindingResult){ if (bindingResult.hasErrors()){ List allErrors = bindingResult.getAllErrors(); ObjectError objectError = allErrors.get(0); System.out.println(objectError.getDefaultMessage()); System.out.println(objectError.getObjectName()); System.out.println(allErrors); } return "index"; }

The request first comes to the dispatcher servlet's doDispatch method, and eventually calls the ModelAttributeMethodProcessor#resolveArgument method

Constraint Tree #validateSingleConstraint is called after DataBinder#validate method, which calls concrete validator

Specific validators

Thank you for reading, the above is the content of "What are the methods of using BindingResult?" After studying this article, I believe that everyone has a deeper understanding of what is the method of using BindingResult. The specific use situation still needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

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