Java 春天将字符串值从视图传递到模型中的int/Integer参数
我正在学习spring,我遇到了一些无法解释的奇怪行为。 这里我有一个简单的课堂:Java 春天将字符串值从视图传递到模型中的int/Integer参数,java,spring-mvc,Java,Spring Mvc,我正在学习spring,我遇到了一些无法解释的奇怪行为。 这里我有一个简单的课堂: public class Customer { private Integer id; public void setId(Integer id) { this.id = id; } 简单控制器: @Controller @RequestMapping("/customer") public class CustomerController { @InitBi
public class Customer {
private Integer id;
public void setId(Integer id) {
this.id = id;
}
简单控制器:
@Controller
@RequestMapping("/customer")
public class CustomerController {
@InitBinder
public void initBinder(WebDataBinder dataBinder){
StringTrimmerEditor editor = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class,editor);
}
@RequestMapping("/showForm")
public String customerPage(Model model){
model.addAttribute("customer",new Customer());
return "customerPage";
}
@RequestMapping("/showConfirmation")
public String customerConfirmation(@Valid @ModelAttribute("customer") Customer customer, BindingResult result){
System.out.println(customer.getLastName());
if(result.hasErrors())
return "customerPage";
else
return "customerConfirmation";
}
}
下面是customerPage.jsp的一部分:
<body>
<form:form action="showConfirmation" modelAttribute="customer">
Id: <form:input path="id"/>
<form:errors path="id"/>
<input type="submit" value="Submit">
</form:form>
</body>
在编写本文时,查看中的
setAsText
代码:
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(null);
}
else if (this.numberFormat != null) {
// Use given NumberFormat for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
}
else {
// Use default valueOf methods for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass));
}
}
我们看到,如果
allowEmpty
属性为true,则当文本为null或空字符串时,它会将值设置为null。如果该值为false,则不管怎样,它都会尝试从字符串中解析数字值,从而导致错误。在不深入研究代码的情况下,allowEmpty
标志设置为false是合理的,这可能是因为int
是一个原语,不能为null。这似乎不是理想的行为,但当int未赋值时,它将默认为零。您希望抛出异常,而不是将int设置为0,因为这只会掩盖错误 您可以添加错误的stracktrace吗?我认为问题出在StringTrimmerEditor的某个地方。您可以检查它是如何工作的。或者,您可以基于PropertyEditorSupport
实现您自己的自定义编辑器。但是我的@InitBinder
方法中只有StringTrimmerEditor
,尽管堆栈跟踪显示:org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (this.allowEmpty && !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(null);
}
else if (this.numberFormat != null) {
// Use given NumberFormat for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
}
else {
// Use default valueOf methods for parsing text.
setValue(NumberUtils.parseNumber(text, this.numberClass));
}
}