使用Thymeleaf和Java Spring时如何检查输入是否为数字?

问题描述

我有一个货币转换器,并且如果我在输入字段中输入一个字符串,则在我的任何支票都可以用作输入值与控制器中声明的值不匹配之前,会出现错误。我的控制器:

@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");
                }

双倍金额是相关属性

在HTML页面中,输入没有什么特别的:

                        <div class="float-right">
                            <input type="text" class="form-control" placeholder="Amount"
                                id="amount" name="amount">
                        </div>

我可以看到问题在于该错误是由于变量的声明引起的。

所以我的问题是如何在输入到控制器之前检查输入?

解决方法

在提交请求之前验证输入字段的类型或添加spring的验证程序是不够的

,

一种更简单的方法是将String作为方法参数。

例如

@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
    }
,

您的输入元素是否需要为文本类型,并且必须使用多少个小数位?例如,<input type="number" step="0.01">允许您输入带有两个小数的数字值。 Input type number documentation