【问题标题】:can't apply custom validation to requestParam无法将自定义验证应用于 requestParam
【发布时间】:2019-07-29 13:42:46
【问题描述】:

我有我的 RequestParam,我需要验证它,但我的控制器不适用 mu 自定义验证

@RestController
@Validated
class ExchangeController {

    private static final Logger logger = Logger.getLogger(ExchangeController.class.getName());

    @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
    @Autowired
    @Qualifier("dataService")
    private CurrencyExchangeService currencyExchangeService;

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
    public Object converting(@RequestParam("fromCurrency") @NotNull @CurrencyValidation String fromCurrency,
                             @RequestParam("toCurrency") @NotNull String toCurrency,
                             @RequestParam("amount") @NotNull String amount) throws IOException {
        BigDecimal convertedAmount = currencyExchangeService.convert(fromCurrency, toCurrency, new BigDecimal(amount));
        return new ExchangeRateDTO(fromCurrency, toCurrency, new BigDecimal(amount), convertedAmount);

    }
}

和自定义验证

public class ConstractCurrencyValidator implements
            ConstraintValidator<CurrencyValidation, String> {
        @Override
        public void initialize(CurrencyValidation currency) {
        }

        @Override
        public boolean isValid(String currency, ConstraintValidatorContext constraintValidatorContext) {
            return currency != null && Currency.getAvailableCurrencies().contains(Currency.getInstance(currency));
        }
    }

【问题讨论】:

  • 在此处发布您的CurrencyValidation 课程,您的预期结果是什么?
  • @rimonmostafiz 我希望如果我输入的不是货币,我会收到 400 错误
  • 您收到什么错误?
  • @rimonmostafiz 不适用于参数
  • 日志中是否有ConstraintViolationException异常?

标签: java spring-boot validation controller http-request-parameters


【解决方案1】:

需要在我的@interface CustomValidation 中添加注释。这意味着验证也可以用于参数。

@Target({ ElementType.PARAMETER })

【讨论】:

  • 在您的问题中包含所有这些,以便将来可能对某人有所帮助
【解决方案2】:

在配置中启用参数验证:

 @Bean
public Validator validator() {
    return new LocalValidatorFactoryBean();
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
    methodValidationPostProcessor.setValidator(validator());
    return methodValidationPostProcessor;
}

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 2016-08-17
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多