Reputation: 47
I have a Currency converter and if I enter a string into the input field I get an error before any of my checks can be used as the input value doesn't match what is declared in the controller. My Controller:
@RequestMapping(value = "/index", method = RequestMethod.POST)
public String convertCurrency(@RequestParam String toCurrency, Double amount, Model model,
RedirectAttributes redirectAttributes) {
if (!(amount == null)&&(amount== (double)amount)) {
if (amount > 0) {
try {
ConvertionCurrency currency = currencyService.getCurrencyRate(toCurrency);
Double conRate = currency.getConvertionRateToEUR();
Double result = amount * conRate;
System.out.println(result);
redirectAttributes.addFlashAttribute("result", result);
redirectAttributes.addFlashAttribute("successClass", "alert-success");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("message", "A positive number is needed");
redirectAttributes.addFlashAttribute("alertClass", "alert-danger");
}
Double amount is the attribute in question.
In the HTML page the input is nothing special:
<div class="float-right">
<input type="text" class="form-control" placeholder="Amount"
id="amount" name="amount">
</div>
I can see that the problem is that the error is caused in the declaration of the variables.
So my question is how do I check the input before it goes to the Controller?
Upvotes: 0
Views: 1054
Reputation: 2266
Does your input element need to be of type text, and how many decimal places do you have to work with? <input type="number" step="0.01">
would allow you to enter numeric values with two decimals, for example. Input type number documentation
Upvotes: 1
Reputation: 125
A simpler way of doing that is to take a String
as the method arguments.
e.g.
@RequestMapping(value = "/index", method = RequestMethod.POST)
public String convertCurrency(@RequestParam String toCurrency, String amount, Model model,
RedirectAttributes redirectAttributes) {
try {
Double foo = Double.valueOf(amount);
try {
// Your code here
} catch (...) {...}
} catch (NumberFormatException e) {
// Handle your error when the input is a String
}
Upvotes: 1
Reputation: 11
It is not enough to verify the type of the input field before submitting the request, or add spring's verifier
Upvotes: 1