【发布时间】:2018-02-06 18:59:47
【问题描述】:
我正在开发一个 Spring Web 应用程序,并且我有一个具有 Integer 属性的实体,用户可以在使用 JSP 表单创建新实体时填写该属性。该表单调用的控制器方法如下:
@RequestMapping(value = {"/newNursingUnit"}, method = RequestMethod.POST)
public String saveNursingUnit(@Valid NursingUnit nursingUnit, BindingResult result, ModelMap model)
{
boolean hasCustomErrors = validate(result, nursingUnit);
if ((hasCustomErrors) || (result.hasErrors()))
{
List<Facility> facilities = facilityService.findAll();
model.addAttribute("facilities", facilities);
setPermissions(model);
return "nursingUnitDataAccess";
}
nursingUnitService.save(nursingUnit);
session.setAttribute("successMessage", "Successfully added nursing unit \"" + nursingUnit.getName() + "\"!");
return "redirect:/nursingUnits/list";
}
验证方法只是检查数据库中是否已经存在该名称,因此我没有包含它。我的问题是,当我故意在字段中输入文本时,我希望有一个很好的消息,例如“自动放电时间必须是数字!”。相反,Spring 返回这个绝对可怕的错误:
Failed to convert property value of type [java.lang.String] to required type [java.lang.Integer] for property autoDCTime; nested exception is java.lang.NumberFormatException: For input string: "sdf"
我完全理解为什么会发生这种情况,但我一生都无法弄清楚如何以编程方式将 Spring 的默认数字格式异常错误消息替换为我自己的。我知道可以用于此类事情的消息源,但我真的想直接在代码中实现这一点。
编辑
按照建议,我在控制器中构建了此方法,但仍然收到 Spring 的“无法转换属性值...”消息:
@ExceptionHandler({NumberFormatException.class})
private String numberError()
{
return "The auto-discharge time must be a number!";
}
其他编辑
这是我的实体类的代码:
@Entity
@Table(name="tblNursingUnit")
public class NursingUnit implements Serializable
{
private Integer id;
private String name;
private Integer autoDCTime;
private Facility facility;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
@Size(min = 1, max = 15, message = "Name must be between 1 and 15 characters long")
@Column(nullable = false, unique = true, length = 15)
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@NotNull(message = "The auto-discharge time is required!")
@Column(nullable = false)
public Integer getAutoDCTime()
{
return autoDCTime;
}
public void setAutoDCTime(Integer autoDCTime)
{
this.autoDCTime = autoDCTime;
}
@ManyToOne (fetch=FetchType.EAGER)
@NotNull(message = "The facility is required")
@JoinColumn(name = "id_facility", nullable = false)
public Facility getFacility()
{
return facility;
}
public void setFacility(Facility facility)
{
this.facility = facility;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof NursingUnit)
{
NursingUnit nursingUnit = (NursingUnit)obj;
if (Objects.equals(id, nursingUnit.getId()))
{
return true;
}
}
return false;
}
@Override
public int hashCode()
{
int hash = 3;
hash = 29 * hash + Objects.hashCode(this.id);
hash = 29 * hash + Objects.hashCode(this.name);
hash = 29 * hash + Objects.hashCode(this.autoDCTime);
hash = 29 * hash + Objects.hashCode(this.facility);
return hash;
}
@Override
public String toString()
{
return name + " (" + facility.getCode() + ")";
}
}
还有一次编辑
我可以使用包含以下内容的类路径上的 message.properties 文件来完成这项工作:
typeMismatch.java.lang.Integer={0} must be a number!
以及配置文件中的以下 bean 声明:
@Bean
public ResourceBundleMessageSource messageSource()
{
ResourceBundleMessageSource resource = new ResourceBundleMessageSource();
resource.setBasename("message");
return resource;
}
这给了我正确的错误消息,而不是我可以忍受的 Spring 泛型 TypeMismatchException / NumberFormatException,但我仍然想尽可能以编程方式完成所有事情,我正在寻找替代方案。
感谢您的帮助!
【问题讨论】:
-
当然。我正在尝试使我的应用程序尽可能简单,因此当有人错误地(或在我的情况下故意)在“映射”到的字段中输入文本时,我试图使从服务器返回的错误更好一点一个整数值。
-
好吧,我猜是这样。我建议的解决方案也在官方文档中进行了描述,它应该可以工作。我会用一个链接更新答案,也许它可以帮助你理解为什么它不起作用。
-
谢谢,我会阅读这篇文章,看看我是否发现我做错了什么。
-
@Martin Hi Martin,你用的是什么版本的 spring?
-
5.0.4 现在,虽然我想在不久的将来升级到最新版本。
标签: java spring replace message numberformatexception