我想知道如何在函数validate()中显示我的模型中的错误消息,当提交不是“有效”时返回“无效的用户名或密码”
index.scala.html
@(myForm: Form[models.profile.MUser])
@import helper._
@import helper.twitterBootstrap._
@main("welcome") {
<h1>Login with your account</h1>
@helper.form(action = routes.Application.loginAccount()) {
@helper.inputText(myForm("username"),'_showConstraints -> false)
@helper.inputPassword(myForm("password"),'_showConstraints -> false)
<input type="submit" value="Login">
}}
Application.java
public static Result loginAccount() {
Form<MUser> filledform = loginForm.bindFromRequest();
if (filledform.hasErrors()) {
Logger.debug("unsuccessfull loggin");
return badRequest(index.render(filledform));
}
MUser user = filledform.get();
SessionCache.setCache(SessionCache.Constants.LOGGED_IN_USER,
UserController.findUserByUserName(user.username));
return redirect("/home");
}
MUser.java package models.profile;
import controllers.services.UserController;
import models.entities.UserDTO;
import play.data.validation.Constraints.*;
import scala.Serializable;
/**
* @author fbranchetti
*
*/
public class MUser implements Serializable{
@Required
public String username;
@Required
public String password;
public String validate() {
if (authenticate(username, password)) {
return "Invalid username or password";
}
return null;
}
private boolean authenticate(String username, String password) {
UserDTO fUser = new UserDTO();
fUser.setPassword(password);
fUser.setUsername(username);
return !UserController.logginUser(fUser);
}
}
答案 0 :(得分:1)
您可以将身份验证的结果存储在Flash变量中。 在视图中,您可以检查变量是否存在并显示它。