gpt4 book ai didi

java - 输入字段的验证

转载 作者:行者123 更新时间:2023-11-30 10:01:52 26 4
gpt4 key购买 nike

在我的应用程序中,我在地址栏中输入了三个参数的值,fromCurrencytoCurrencyamount在 Controller 中。我想检查输入数据的正确性。但是我在测试期间产生了一个异常,没有进一步的进展那些。我需要一个代码,该代码在 Controller 中将检查输入数据的正确性,并根据出错的字段产生第 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 来验证 Controller 的 @RequestParam

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

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

然后你必须通过像这样添加 @Validated 注解来为你的 Controller 中的请求参数和路径变量启用验证

@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

关于java - 输入字段的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com