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

huangapple go评论74阅读模式
英文:

How to check if input is numeral when using Thymeleaf and 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");
            }
            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 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 = &quot;/index&quot;, method = RequestMethod.POST)
	public String convertCurrency(@RequestParam String toCurrency, Double amount, Model model,
			RedirectAttributes redirectAttributes) {
		
		if (!(amount == null)&amp;&amp;(amount== (double)amount)) {
			if (amount &gt; 0) {
				try {
					ConvertionCurrency currency = currencyService.getCurrencyRate(toCurrency);
					Double conRate = currency.getConvertionRateToEUR();

					Double result = amount * conRate;
					System.out.println(result);
					redirectAttributes.addFlashAttribute(&quot;result&quot;, result);
					redirectAttributes.addFlashAttribute(&quot;successClass&quot;, &quot;alert-success&quot;);
				} catch (Exception e) {
					redirectAttributes.addFlashAttribute(&quot;message&quot;, &quot;A positive number is needed&quot;);
					redirectAttributes.addFlashAttribute(&quot;alertClass&quot;, &quot;alert-danger&quot;);
				}

Double amount is the attribute in question.

In the HTML page the input is nothing special:

                        &lt;div class=&quot;float-right&quot;&gt;
							&lt;input type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Amount&quot;
								id=&quot;amount&quot; name=&quot;amount&quot;&gt;
						&lt;/div&gt;

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?

答案1

得分: 1

这不仅仅是在提交请求之前验证输入字段的类型,或者添加 Spring 的验证器就足够了。

英文:

It is not enough to verify the type of the input field before submitting the request, or add spring's verifier

答案2

得分: 1

一个更简单的方法是将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 {
            // 在这里添加你的代码
        } catch (...) {...}
    } catch (NumberFormatException e) {
        // 当输入为字符串时处理错误
    }
}
英文:

A simpler way of doing that is to take a String as the method arguments.

e.g.

@RequestMapping(value = &quot;/index&quot;, 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
    }

答案3

得分: 1

你的输入元素需要是文本类型吗?你需要处理多少位小数?例如,<input type="number" step="0.01"> 可以让你输入带有两位小数的数值。数字输入类型文档

英文:

Does your input element need to be of type text, and how many decimal places do you have to work with? &lt;input type=&quot;number&quot; step=&quot;0.01&quot;&gt; would allow you to enter numeric values with two decimals, for example. Input type number documentation

huangapple
  • 本文由 发表于 2020年8月24日 00:23:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63549349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定