开发者

Customize how Time field is populated from HTTP request

I have a java.sql.Time field in a model that I'm trying to populate from a form submission. Whatever format it's expecting for those values isn't the one(s) I want to use, validation always results in "Incorrect value".

How can I customize the parsing for these values? I thought I'd seen how to do it a while back but I can't find that info 开发者_运维知识库now that I actually need it.


The magic word was "binding". What I need to do is create a custom global binder.

Update: here's my custom binder that will handle several different time formats:

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");
    }
}

I put this in app/lib which works fine, I'm still debating whether this the "right" place for it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜