java - Playframework 临时表单验证已执行,但未按预期工作

标签 java forms playframework-2.2

我有 Login 类,其 validate 方法如下:

public static class Login {

        /** The customer. */
        @ManyToOne
        @Constraints.Required
        public Customer customer;

        /** The password. */
        public String password;


        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public Customer getCustomer() {
            return this.customer;
        }
        public void setCustomer(Customer c) {
            this.customer = c;
        }

        /**
         * Validate.
         *
         * @return the string
         */
        @Transactional
        public String validate() {
            return "Global error";
        }



    }

表单绑定(bind)代码:

Form<Login> filledLoginForm = form(Login.class);
filledLoginForm.bindFromRequest();

当我按如下方式验证表单时:

if (filledLoginForm.hasGlobalErrors()) {
    return badRequest(views.html.login.render(filledLoginForm));
} else if (filledLoginForm.hasErrors()) {
    return badRequest(views.html.login.render(filledLoginForm));
} else {
    return ok("OK");
}

查看:

<input type="hidden" id="customer_id" name="customer.id" value="@customer.id" />


                                @inputPassword(
                                    LoginForm("password"),
                                    '_label -> "Hasło",
                                    '_showConstraints -> false,
                                    '_showErrors -> false
                                )

我得到了正常的页面,就像没有错误一样,但在验证方法中我已经声明了它。

我用的是play 2.2.6

最佳答案

我建议您在 Controller 中明确检查这一点。像这样的东西:

final String cId = form().bindFromRequest().get("customer.id");
if (filledLoginForm.hasGlobalErrors()
        || cId==null || cId.equals("")) {
    // in this case either there were some validation errors or the provided customer.id is not valid
    return badRequest(yourTemplateHere.render(filledLoginForm));
}

您可以尝试的另一种选择是稍微重写您的 validate() 方法并在那里进行检查(假设您的 Customer 中有一个 id 字段) 类):

public String validate() {
    return Customer.id != null ? null : "Oh no, the customer id is empty";
}

附注同时拥有公共(public)字段和 setter/getter 有点令人困惑 - 切换到公共(public)字段或将它们设为私有(private)并使用 getter 和 setter

关于java - Playframework 临时表单验证已执行,但未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31718786/

相关文章:

java - 在身份验证之前重写入站 Java 服务器授权 header

c# - 线程启动期间的竞争条件?

scala - Play2.2.x、BodyParser、身份验证和 Future[结果]

java - AWS Java SDK - 使用区域方法时 Jackson 中的 NoSuchMethodError

Java : "GC Overhead limit exceeded" despite plenty of memory to allocate available

c# - HttpWebRequest:如何通过带有 x-www-form-enclosed 的 WebRequest 查找加拿大邮政的邮政编码?

php - 为什么 htmlspecialchars 在表单发布的 'PHP_SELF' 上工作,而不在 'REQUEST_URI' 上工作?

scala - SecureSocial : Running DB IO in a separate thread pool

scala - 在不使用 Try/Catch block 的情况下如何编写此代码?

java - textView如何显示文本