Java 春天如何使用PropertyEditor转换对象属性?
我有一个带有Spring表单的jsp页面:Java 春天如何使用PropertyEditor转换对象属性?,java,spring,propertyeditor,Java,Spring,Propertyeditor,我有一个带有Spring表单的jsp页面: <form:form id="edit-form" method="POST" commandName="item" action="items"> <form:input id="title" path="title" type="text" /> <form:textarea id="description" path="description"><
<form:form id="edit-form" method="POST" commandName="item"
action="items">
<form:input id="title" path="title" type="text" />
<form:textarea id="description" path="description"></form:textarea>
<form:input id="timeLeft" type="text" path="timeLeft" />
<button type="submit" id="sell-item">Create/Edit</button>
</form:form>
TimeleftPropertyEditor:
public class TimeleftPropertyEditor extends PropertyEditorSupport {
private static final int MILLIS_IN_HOUR = 60 * 60 * 1000;
private static final int MILLIS_IN_MINUTE = 60 * 1000;
@Override
public void setAsText(String text) throws IllegalArgumentException {
Long result = null;
if (text != null) {
String[] time = text.split(":");
if (time.length != 1) {
long hours = Long.parseLong(time[0]) * MILLIS_IN_HOUR;
long minutes = Long.parseLong(time[1]) * MILLIS_IN_MINUTE;
result = hours + minutes;
} else {
result = -1L;
}
}
setValue(result);
}
}
但请求提交时setAsText方法未调用。
BindingResult对象有错误:[字段'timeLeft'上的对象'item'中的字段错误:拒绝值[12:33];代码[typeMismatch.item.timeLeft,typeMismatch.timeLeft,typeMismatch.java.lang.Long,typeMismatch];参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[item.timeLeft,timeLeft];参数[];默认消息[timeLeft]];默认消息[未能将类型为“java.lang.String”的属性值转换为属性“timeLeft”所需的类型“java.lang.Long”;嵌套异常为java.lang.NumberFormatException:对于输入字符串:“12:33”]]long是long而不是string。在init活页夹中,您可以告诉string如何使用此编辑器。另外,您可能不想为所有字段注册它,所以您可能希望将其配置为type
long.class
和特定字段名。@M.Deinum哇!谢谢!它正在工作。非常感谢!
public class TimeleftPropertyEditor extends PropertyEditorSupport {
private static final int MILLIS_IN_HOUR = 60 * 60 * 1000;
private static final int MILLIS_IN_MINUTE = 60 * 1000;
@Override
public void setAsText(String text) throws IllegalArgumentException {
Long result = null;
if (text != null) {
String[] time = text.split(":");
if (time.length != 1) {
long hours = Long.parseLong(time[0]) * MILLIS_IN_HOUR;
long minutes = Long.parseLong(time[1]) * MILLIS_IN_MINUTE;
result = hours + minutes;
} else {
result = -1L;
}
}
setValue(result);
}
}