播放框架无法识别错误?

时间:2014-09-03 05:53:22

标签: java playframework playframework-2.2

我正在尝试通过HTML表单提交POST请求时捕获验证错误。我的Application.java课程中包含以下代码:

public class Application extends Controller
{
    ..

    public static Result addSubscriber()
    {
        Form<Subscriber> subscriberForm = Form.form(Subscriber.class);
        subscriberForm.bindFromRequest();
        Logger.warn(subscriberForm.toString());
        if (!(subscriberForm.hasErrors() || subscriberForm.hasGlobalErrors()))
        {
            Logger.error("dammit");
        }
        else // never reaches here
        ...
    }
}

在我的Subscriber.java课程中:

@Entity
public class Subscriber extends Model
{
    @Id
    public String email;

    @CreatedTimestamp
    Timestamp createdAt;

    ...

    public List<ValidationError> validate()
    {
        List<ValidationError> errors = new ArrayList<ValidationError>();

        Pattern p = Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$");
        Matcher m = p.matcher(email);
        if (!m.find())
        {
            Logger.error("\"" + email + "\" appears to be an invalid email.");
            errors.add(new ValidationError("email", "\"" + email + "\" appears to be an invalid email."));
        }

        if (Subscriber.exists(email))
        {
            Logger.error("\"" + email + "\" is already subscribed!");
            errors.add(new ValidationError("subscribed", "\"" + email + "\" is already subscribed!"));
        }

        Logger.warn("whoa!!!!!! " + errors.toString());

        //return errors.isEmpty() ? null : errors;
        return errors;
    }
}

尝试输入无效电子邮件时的结果:

[error] application - "wofutn@nufwu" appears to be an invalid email.
[warn] application - whoa!!!!!! [ValidationError(email,"wofutn@nufwu" appears to be an invalid email.,[])]
[warn] application - Form(of=class models.Subscriber, data={}, value=None, errors={})
[error] application - dammit

为什么错误列表为空?!据我所知I am following directions。无论如何,我似乎无法触发错误。

我正在使用Play 2.2.2 this appears to be the relevant source code file。我不会立即看到我做错了什么。

1 个答案:

答案 0 :(得分:1)

bindFromRequest()方法不会改变对象,而是返回表单的新实例。换句话说,您的错误未分配给任何内容,因为您在应用验证之前处理对象。只需按以下方式更改即可解决问题。

Form<Subscriber> subscriberForm = Form.form(Subscriber.class);
subscriberForm  = subscriberForm.bindFromRequest();
相关问题