验证输入字段

时间:2019-07-29 09:55:35

标签: java spring-boot exception currency

在我的应用程序中,我将三个参数fromCurrencytoCurrencyamount的值输入到地址栏中 并在控制器中。我想检查输入数据的正确性。但是我在测试过程中产生了一个异常,没有进一步的处理 那些。我需要一个代码,该代码在控制器中将检查输入数据的正确性,并根据产生错误的字段,将产生第400个错误,并带有错误填充的字段名称

我尝试使用

进行此验证
if(!Currency.getAvailableCurrencies().contains(Currency.getInstance(fromCurrency)))

但是如果Currency不包含fromCurrency

,它将生成异常。
@RestController
class ExchangeController {

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

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

    @SuppressWarnings("SameReturnValue")
    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
    public String start() {
        return "input parameters";
    }

    @RequestMapping(value = "/convert", method = RequestMethod.GET, produces = "application/json")
    public ExchangeRateDTO converting(@RequestParam("fromCurrency") String fromCurrency,
                                      @RequestParam("toCurrency") String toCurrency,
                                      @RequestParam("amount") String amount) throws IOException {
        if (!Currency.getAvailableCurrencies().contains(Currency.getInstance(fromCurrency))) {

        }
        BigDecimal convertedAmount = currencyExchangeService.convert(fromCurrency, toCurrency, new BigDecimal(amount));
        return new ExchangeRateDTO(fromCurrency, toCurrency, new BigDecimal(amount), convertedAmount);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Hibernate Validator来验证控制器的@RequestParam

将此依赖项添加到您的pom.xml

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.10.Final</version>
</dependency>

然后,您必须通过添加@Validated这样的注释来在控制器中启用请求参数和路径变量的验证

@RestController
@RequestMapping("/")
@Validated
public class Controller {
    // ...
}

然后,您可以将@NotNull @Min @Max之类的注释添加到您的RequestParam Like

@RequestMapping(value = "/convert", method = RequestMethod.GET, produces = "application/json")
    public ExchangeRateDTO converting(@RequestParam("fromCurrency") @NotNull @NotBlank @Size(max = 10) String fromCurrency,
                                      @RequestParam("toCurrency") String toCurrency,
                                      @RequestParam("amount") String amount) throws IOException {
        if (!Currency.getAvailableCurrencies().contains(Currency.getInstance(fromCurrency))) {

        }
        BigDecimal convertedAmount = currencyExchangeService.convert(fromCurrency, toCurrency, new BigDecimal(amount));

您还可以根据需要定义自定义注释。

还有更详细,更漂亮的文章here