gpt4 book ai didi

java - Spring MVC : Failed to convert property value of type String to Integer

转载 作者:行者123 更新时间:2023-11-30 11:02:09 25 4
gpt4 key购买 nike

我的代码是这样的

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

最佳答案

您可以添加 exception handler给你的 Controller 来处理 NumberFormatExcpetion。

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

关于java - Spring MVC : Failed to convert property value of type String to Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com