in my application, I enter the values of the three parameters, fromCurrency
, toCurrency
, and amount
into the address bar
and in the controller. I want to check the correctness of the entered data. But I have generated an exception during the test and nothing goes further
Those. I need a code that in the controller will check the correctness of the entered data and, depending on the field in which the error was made, will produce a 400th error with the name of the incorrectly filled field
I'm tried this validation, with
if(!Currency.getAvailableCurrencies().contains(Currency.getInstance(fromCurrency)))
but it's generate exception if Currency doesn't contain 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);
}
}
You can use Hibernate Validator to validate the @RequestParam
of your controller.
Add this dependency to your pom.xml
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.10.Final</version>
</dependency>
Then you have to enable validation for both request parameters and path variables in your controllers by adding the @Validated
annotation like this
@RestController
@RequestMapping("/")
@Validated
public class Controller {
// ...
}
Then you can add Annotations like @NotNull
@Min
@Max
to your 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));
You can also define custom annotations for your needs.
There is more detailed and nice article here