Spring Boot:请求参数中的自定义验证 [英] Spring Boot : Custom Validation in Request Params

查看:84
本文介绍了Spring Boot:请求参数中的自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证控制器中的请求参数之一. request参数应该来自给定值列表之一,否则,将引发错误.在下面的代码中,我希望请求参数orderBy来自@ValuesAllowed中存在的值列表.

I want to validate one of the request parameters in my controller . The request parameter should be from one of the list of given values , if not , an error should be thrown . In the below code , I want the request param orderBy to be from the list of values present in @ValuesAllowed.

@RestController
@RequestMapping("/api/opportunity")
@Api(value = "Opportunity APIs")
@ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount",
        "ApplicationsApprovedCount" })
public class OpportunityController {

@GetMapping("/vendors/list")
    @ApiOperation(value = "Get all vendors")

    public ResultWrapperDTO getVendorpage(@RequestParam(required = false) String term,
            @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
            @RequestParam(required = false) String orderBy, @RequestParam(required = false) String sortDir) {

我已经编写了一个自定义bean验证器,但不知何故,它不起作用.即使传递查询参数的任何随机值,它也不会验证并抛出错误.

I have written a custom bean validator but somehow this is not working . Even if am passing any random values for the query param , its not validating and throwing an error.

@Repeatable(ValuesAllowedMultiple.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {ValuesAllowedValidator.class})
public @interface ValuesAllowed {

    String message() default "Field value should be from list of ";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    String propName();
    String[] values();
}

public class ValuesAllowedValidator implements ConstraintValidator<ValuesAllowed, Object> {

    private String propName;
    private String message;
    private String[] values;

    @Override
    public void initialize(ValuesAllowed requiredIfChecked) {
        propName = requiredIfChecked.propName();
        message = requiredIfChecked.message();
        values = requiredIfChecked.values();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        Boolean valid = true;
        try {
            Object checkedValue = BeanUtils.getProperty(object, propName);

            if (checkedValue != null) {
                valid = Arrays.asList(values).contains(checkedValue.toString().toLowerCase());
            } 

            if (!valid) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(message.concat(Arrays.toString(values)))
                        .addPropertyNode(propName).addConstraintViolation();
            }
        } catch (IllegalAccessException e) {
            log.error("Accessor method is not available for class : {}, exception : {}", object.getClass().getName(), e);
            return false;
        } catch (NoSuchMethodException e) {
            log.error("Field or method is not present on class : {}, exception : {}", object.getClass().getName(), e);
            return false;
        } catch (InvocationTargetException e) {
            log.error("An exception occurred while accessing class : {}, exception : {}", object.getClass().getName(), e);
            return false;
        }
        return valid;
    }
}

推荐答案

案例1:如果根本未触发注记ValuesAllowed,则可能是因为未使用@Validated注释控制器.

Case 1: If the annotation ValuesAllowed is not triggered at all, it could be because of not annotating the controller with @Validated.

    @Validated
    @ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount",
                        "ApplicationsApprovedCount" })
    public class OpportunityController {
    @GetMapping("/vendors/list")
    public String getVendorpage(@RequestParam(required = false) String term,..{
    }

情况2:如果触发并引发错误,则可能是由于BeanUtils.getProperty无法解析属性并引发异常.

Case 2: If it is triggered and throwing an error, it could be because of the BeanUtils.getProperty not resolving the properties and throwing exceptions.

如果上述解决方案不起作用,则可以尝试将注释移至方法级别,并更新Validator以将有效值列表用于OrderBy参数.这对我有用.下面是示例代码.

If the above solutions do not work, you can try moving the annotation to the method level and update the Validator to use the list of valid values for the OrderBy parameter. This worked for me. Below is the sample code.


    @RestController
    @RequestMapping("/api/opportunity")
    @Validated
    public class OpportunityController {
        @GetMapping("/vendors/list")
        public String getVendorpage(@RequestParam(required = false) String term,
                @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size,
                @ValuesAllowed(propName = "orderBy", values = { "OpportunityCount", "OpportunityPublishedCount", "ApplicationCount",
                        "ApplicationsApprovedCount" }) @RequestParam(required = false) String orderBy, @RequestParam(required = false) String sortDir) {
            return "success";
        }

    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = { ValuesAllowed.Validator.class })
    public @interface ValuesAllowed {

        String message() default "Field value should be from list of ";

        Class<?>[] groups() default {};

        Class<? extends Payload>[] payload() default {};

        String propName();

        String[] values();

        class Validator implements ConstraintValidator<ValuesAllowed, String> {
            private String propName;
            private String message;
            private List<String> allowable;

            @Override
            public void initialize(ValuesAllowed requiredIfChecked) {
                this.propName = requiredIfChecked.propName();
                this.message = requiredIfChecked.message();
                this.allowable = Arrays.asList(requiredIfChecked.values());
            }

            public boolean isValid(String value, ConstraintValidatorContext context) {
                Boolean valid = value == null || this.allowable.contains(value);

                if (!valid) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate(message.concat(this.allowable.toString()))
                            .addPropertyNode(this.propName).addConstraintViolation();
                }
                return valid;
            }
        }
    }

这篇关于Spring Boot:请求参数中的自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆