简体   繁体   中英

Spring boot - Combine DTO and form validation

I am currently developing an API where I'm using DTO for the first time. So far I've used Spring's form validation with javax.validation .

So my question is if there is a way to combine both DTO and "form" validation. Let me explain myself: lets say I have a service to log in and another to register. In the service to register we have: name, password and email, the 3 of them must be filled. As for the login service, only the email and password must be filled. So we'd have something like:

private String name;
private String password;
private String email;

Until now, what I did was to create a POJO per request (forms) and then use annotations such as @NotNull but now with DTO in the project I'm in now they just have the same DTO and business object with the same properties and no constraints.

How could I do what I was usually doing? Checking the fields that must be not null in the controller looks a little dirty to me and I can't just put something like @NotNull in the UserDTO because then in the two examples I said I'd have to send also the name when logging in although it's not needed for that service.

So, how could I combine these 2 things? Is this something not possible or there's a better approach?

Thanks.

I assume you are using two separate controllers for login and register requests. And if it is the case, then you can make good use of org.springframework.validation.Validator interface:

@Component("registrationValidator")
public class RegistrationValidatorImpl implements Validator {

    @Override
    public boolean supports(final Class<?> aClass) {
    }

    @Override
    public void validate(final Object o, final Errors errors) {
    }
}

Create RegistrationValidatorImpl and LoginValidatorIml and @Autowire it in your controllers.

The usage of validator is simple:

invokeValidator(registrationValidator, someDTO, errors);

if (errors.hasErrors()) {
    return new ResponseEntity(HttpStatus.BAD_REQUEST); //or whatever logic here
}

The controller method signature should be similar to this:

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity register(@RequestBody final SomeDTO someDTO, final HttpServletRequest request, final Errors errors) {}

I case of one controller, I assume you have different methods mapped to login and register requests. You can @Autowire both validators in controller and use each in separate methods.

Using groups for validation with javax.validation did the work. I followed the answer in this question (as Andrew suggested), then I just had to put every field I wanted to have different rules in different groups.

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