I have jsp page with Spring form:
<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>
On the clienside timeleft format: HH:MM, but on serverside we need to convert it to milliseconds (Long). How to do that (From client comes Item object with(title, description, timeleft fields))? How to convert specific property in custom object?
I'm trying to do something like that:
Controller class with the initBinder method:
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, "item.timeLeft",
new TimeleftPropertyEditor());
}
@RequestMapping(method = RequestMethod.POST)
public void create(@ModelAttribute("item") Item item, BindingResult result) {
System.out.println(item + ": " +result.getAllErrors());
}
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);
}
}
But setAsText method not invoking when request comming. BindingResult object have errors: [Field error in object 'item' on field 'timeLeft': rejected value [12:33]; codes [typeMismatch.item.timeLeft,typeMismatch.timeLeft,typeMismatch.java.lang.Long,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [item.timeLeft,timeLeft]; arguments []; default message [timeLeft]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Long' for property 'timeLeft'; nested exception is java.lang.NumberFormatException: For input string: "12:33"]]