1
我有一个java.sql.Time
字段在我试图从表单提交填充的模型中。无论对于这些值所期望的格式都不是我想要使用的格式,验证总是会导致“错误的值”。自定义如何从HTTP请求填充时间字段
如何为这些值自定义解析?我以为我已经看到了如何做一段时间,但现在我无法找到这个信息,我真的需要它。
我有一个java.sql.Time
字段在我试图从表单提交填充的模型中。无论对于这些值所期望的格式都不是我想要使用的格式,验证总是会导致“错误的值”。自定义如何从HTTP请求填充时间字段
如何为这些值自定义解析?我以为我已经看到了如何做一段时间,但现在我无法找到这个信息,我真的需要它。
魔术字是“绑定”。我需要做的是创建一个custom global binder。
更新:这是我的定制绑定将处理几个不同的时间格式:
import play.data.binding.*;
import org.joda.time.format.*;
import java.lang.annotation.*;
import java.sql.Time;
import java.text.ParseException;
import java.util.regex.*;
@Global
public class SqlTimeBinder implements TypeBinder<Time> {
private static final Pattern TWELVE_HOUR = Pattern.compile("^\\d{1,2}:\\d{2}[ap][m]?$", Pattern.CASE_INSENSITIVE);
private static final Pattern TWELVE_HOUR_SHORT = Pattern.compile("^\\d{1,2}[ap][m]?$", Pattern.CASE_INSENSITIVE);
private static final Pattern TWENTYFOUR_HOUR = Pattern.compile("^\\d{1,2}:\\d{2}$");
private DateTimeFormatter twelve_hour = DateTimeFormat.forPattern("h:ma");
private DateTimeFormatter twelve_hour_no_minutes = DateTimeFormat.forPattern("ha");
private DateTimeFormatter twenty_four_hour = DateTimeFormat.forPattern("H:m");
public Object bind(String name, Annotation[] annotations, String value, Class clazz, java.lang.reflect.Type genericType) {
if (value == null || value.length() == 0) {
return null;
}
Matcher m = TWELVE_HOUR.matcher(value);
if (m.matches()) {
return new java.sql.Time(twelve_hour.parseDateTime(value).getMillis());
}
m = TWELVE_HOUR_SHORT.matcher(value);
if (m.matches()) {
return new java.sql.Time(twelve_hour_no_minutes.parseDateTime(value).getMillis());
}
m = TWENTYFOUR_HOUR.matcher(value);
if (m.matches()) {
return new java.sql.Time(twenty_four_hour.parseDateTime(value).getMillis());
}
throw new IllegalArgumentException("Invalid time");
}
}
我把这个app/lib
的正常工作,我仍在争论它是否这个“正确”的地方。