输入字段的验证

validation of the entered field

在我的应用程序中,我将 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);
    }
}

您可以使用 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 {
    // ...
}

然后你可以在你的RequestParam中添加像@NotNull @Min @Max这样的注释 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