Forms 游戏登录表单验证!2 公共静态结果验证(){ Form loginForm=Form(loginForm.class).bindFromRequest(); if(loginForm.hasErrors()){ 返回ok(views.html.Account.index.render(loginForm)); }否则{ 字符串email=loginForm.get().email; User User=User.findByUsername(电子邮件); if(Hash.checkPassword(loginForm.get().password,user.passwordHash)){ //设置会话 会话(“电子邮件”,电子邮件); 返回重定向(routes.UserController.view(user.getId()); }否则{ 返回badRequest(views.html.Account.index.render(loginForm)); } } }

Forms 游戏登录表单验证!2 公共静态结果验证(){ Form loginForm=Form(loginForm.class).bindFromRequest(); if(loginForm.hasErrors()){ 返回ok(views.html.Account.index.render(loginForm)); }否则{ 字符串email=loginForm.get().email; User User=User.findByUsername(电子邮件); if(Hash.checkPassword(loginForm.get().password,user.passwordHash)){ //设置会话 会话(“电子邮件”,电子邮件); 返回重定向(routes.UserController.view(user.getId()); }否则{ 返回badRequest(views.html.Account.index.render(loginForm)); } } },forms,authentication,playframework,form-authentication,Forms,Authentication,Playframework,Form Authentication,我们使用此代码对用户进行身份验证,但我们希望在登录过程中出现问题时显示错误消息(无效用户名/密码等)。然而,我们在网上找不到任何文档,因为大多数关于使用flash处理错误消息的文档都是针对Play1.x的 1) 如何将错误消息添加到此登录功能 2) 如何在视图中访问这些错误消息 3) 一般来说,form类是如何发挥作用的!处理错误的创建和处理(以及我们如何访问它们?) 谢谢!:-) @1)通常通过验证添加错误。因此,您的LoginForm应该有一个validate方法 @2) form.erro

我们使用此代码对用户进行身份验证,但我们希望在登录过程中出现问题时显示错误消息(无效用户名/密码等)。然而,我们在网上找不到任何文档,因为大多数关于使用flash处理错误消息的文档都是针对Play1.x的

1) 如何将错误消息添加到此登录功能

2) 如何在视图中访问这些错误消息

3) 一般来说,form类是如何发挥作用的!处理错误的创建和处理(以及我们如何访问它们?)

谢谢!:-)

@1)通常通过验证添加错误。因此,您的LoginForm应该有一个validate方法

@2) form.errors()或fomr.error(“字段”)和form.globalErrors()


@3) 在绑定时,将创建错误并将其放入表单的构造函数中。但是form.errors().put(key,error)应该可以工作,因为映射没有被复制。但这更像是一种黑客行为,将来可以改变。

我建议
form.withError(“name”,“Error”)

还有
表单。withGlobalError(“Error”)

谢谢您的回答!我们使用@Constraints.Required来验证字段,这将生成所需的错误。我们发现访问这些错误的唯一方法是通过helper FieldElements.errors,或者通过实际的映射本身,这非常麻烦。如果您使用普通的scala tenplate helper,他们会为您打印错误,请参阅表单示例。所以这通常很简单,你不需要做任何事情,只需要使用帮助器。但是我们希望将错误作为一个组打印在字段上方的框中,而不是像示例中那样打印在字段中。知道怎么做吗?只需通过迭代
form.errors()
打印它们,不要使用form-helper。问题是,错误消息不会通过i18n转换器解析以进行内置验证(例如@Constraints.Required将打印出error.Required,而不是“This is Required”等)。虽然我通过在控制器中添加一个hack来解决这个问题,但是我希望有一个更平滑的方法来实现它。
public static Result authenticate() {
    Form<LoginForm> loginForm = form(LoginForm.class).bindFromRequest();

    if (loginForm.hasErrors()) {
        return ok(views.html.Account.index.render(loginForm));
    } else {
            String email = loginForm.get().email;
            User user = User.findByUsername(email);

            if (Hash.checkPassword(loginForm.get().password, user.passwordHash)) {
                // set session
                session("email", email);
                return redirect(routes.UserController.view(user.getId()));
            } else {
                return badRequest(views.html.Account.index.render(loginForm));
            }
        }
}