javax. validation & spring. Bingresult essay

Kenneth Brian Edmund2022-05-14 19:25:46

0. The lesson of invalid annotation verification is that spring mvc Support for ,cxf No way

@Validated and @Valid difference
@NotEmpty etc. JSR-303 annotation groups attribute +BingResult Use
Troubleshooting records of ineffective verification at one time +springmvc Verification implementation of the bottom layer
A simple one demo
simple code stay gitee in
@NotEmpty、@NotBlank、@NotNull The difference between the three annotations


Everything from JSR-303 Specification proposal ,@Valid Is the product of its abstract level …

1. @Validated and @Valid difference

@Valid Support , but @Validated Annotation of object properties is not supported -> If the object attribute needs nested verification, you need to use @Valid

// controller in
@post find(@validated @reqbody Dto dto,BingResult br);
class Dto{
// Nested verification
@Valid
list<User> users;
@NotEmpty
string id;
}

2. Verification exception information is automatically injected into BingResult

BindingResult Need to put @Validated/@Valid After the annotated object

3. @NotEmpty And so on groups attribute

The same verified object is allowed to show different verification behaviors under different circumstances

4. springmvc Low level support for verification logic

Spring Validation It's just an abstraction , The real implementation of parameter verification is hibernate validator

spring mvc What we really do is : Capture by validator Exception thrown , And wrapped in BingResult

5. simple code

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
/** * @Author: weng * @Date: 2022/5/4 * @Description: com.weng.cloud.service8881.javax.validation.controller * * spring controller With the help of @NotNull Annotations can throw exceptions * * The use of such annotations elsewhere seems to be just a document ... */
@RestController
@RequestMapping("/javax/validation/testValidation")
public class TestValidationController {

@RequestMapping(value = "/testNotNull")
public String testNotNull(@Valid User user){

return "i wanna be a friend...";
}
public void testFinal(final String weng){

//do not thing
}
public static void main(String[] args) {

// Compilation is error free -->final null
new TestValidationController().testFinal(null);
}
}
@Data
@AllArgsConstructor
class User{

@NotNull(message = " Ah, ah, ah ")
String name;
//int age;
}

thank
Similar articles

2022-05-14