简体   繁体   中英

How should I validate dependent parameters in @requestparam in spring Rest API?

I know there are validators in spring. However, these validators can only be bound to a single object. Say a Pojo in request body. However, I have a scenario where I have a get request and I want to validate a date range: I have a start date and the end date as @requestparams . How should I validate these?

Also there is a validator applied for the same @restcontroller : for post request, say Employeevalidtor . Can I invoke multiple validators for different objects in the same @restcontroller ?

您可以使用单独的验证器,但它们必须通过传递要验证的相应对象来手动实例化。

I assume you are talking about request binding validations. The same validations can be obtained with Spring Validators for @RequestParam and @PathVariables as mentioned in this post

Adding the relevant piece here. The controller will look something like this:

@RestController
@Validated
public class RegistrationController {
@RequestMapping(method = RequestMethod.GET,
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.OK)
public Map search(@Email @RequestParam("email") String email) {
    return emailMessage(email);
}
}

Note the @Validated method at the class level (which can also be declared at the method level).

Let Spring MVC will map your request parameters to a pojo encapsulating all the related inputs and then add a validator for that.

@RestController
@RequestMapping("/myUrl")
public class MytController {
    private final MyIntervalValidator validator;

    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.setValidator(validator);
    }

    @GetMapping
    public void doSomthing(@Valid @RequestParam MyInterval interval){...}
class MyInterval implements Serializable{
    private Date startDate;
    private Date endDate;
}
import org.springframework.validation.Validator;
class MyIntervalValidator implements Validator{
    @Override
    public boolean supports(Class<?> clazz) {
        return MyInterval.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        final MyInterval params = (MyInterval) target;
        ....
    }
}

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