简体   繁体   中英

Validate only a few properties from user input in a rest service with spring boot

how are you?

I'm developing a rest service with Java and Spring Boot and I have a question about the validations of user input with javax.validation.

Suppose I have a User Model with name and age properties.

And suppose also that I have two endpoints (A and B), and that in endpoint AI need to validate only the name and in endpoint BI need to validate just the age.

The problem I'm facing is that using javax.validation I need to validate the two properties on both endpoints. Is there a way to validate only the fields that i need to validate in certain endpoint? or some way to disable validation on certain properties in an endpoint?

Examples

User public class User {

    @NotEmpty(message="You need to pass the name parameter")
    private String name;

    @NotEmpty(message="You need to pass the age parameter")
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

User RestController

@RestController
@RequestMapping("/v1/user")
public class UserController {

    @Autowired
    private User _user;

    @RequestMapping(value = "/endpoint-a", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public ResponseEntity<?> doPostEndpointA(@Valid @RequestBody User user) {
        // only validate the user name
    }

    @RequestMapping(value = "/endpoint-b", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseBody
    public ResponseEntity<?> doPostEndpointB(@Valid @RequestBody User user) {
        // only validate the user age
    }
}

By putting the validation on the domain class the validation will be performed no matter what end point is called.

If each end point requires different validation put that logic in the controller and remove it from the domain class. If you need to keep the validation on the domain class and only validate one field per end point perhaps default values could solve that for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM