Spring MVC:无法将String类型的属性值转换为Integer

时间:2015-06-17 14:50:35

标签: java spring

我的代码看起来像这样

@RequestMapping(value = "/test2Form", method = RequestMethod.POST)
public String testForm(@ModelAttribute("someBean") SomeBean someBean, BindingResult result) {
    BindException errors = new BindException(someBean, "someBean");
    someValidator.validate(someBean, errors);

    for (FieldError error : errors.getFieldErrors()) {
        result.addError(new FieldError("someBean", error.getField(), error.getCode()));
    }

    // Field error
    if (result.hasErrors()) {
        return "test/test1";
    }

    return "index";
}

public class SomeBean{
    private Integer someInteger;
    // getter and setter
}

这可以正常工作,直到用户通过HTML将值更改为非整数值,例如像这样:http://www.pichost.de/image/9IN

在这种情况下会发生类型不匹配(类似Failed to convert property value of type java.lang.String to required type java.lang.Integer for property someInteger; nested exception is java.lang.NumberFormatException)。 我不想显示此生成的错误消息。相反,我想只显示我的错误消息。这可能吗?

我的JSP看起来像这样:

<form:form action="test2Form.htm" commandName="someBean" method="post">
    <form:select path="someInteger">
        <option value="1">Value 1</option>
        <option value="2">Value 2</option>
        <option value="3">Value 3</option>
    </form:select>
    <form:errors path="someInteger" element="div"/>

    <input type="submit" value="Submit">
</form:form>

1 个答案:

答案 0 :(得分:1)

您可以向控制器添加exception handler以处理NumberFormatExcpetion。

@ExceptionHandler(NumberFormatException.class) 
public String handleNumberFormatException(NumberFormatException e...) {
//add error for view here
}