繁体   English   中英

使用GAE数据存储进行身份验证时,实体用户返回null

[英]Authenticating with GAE Datastore return null on Entity User

我正在尝试创建自己的身份验证。 每次尝试登录时,在GAE数据存储区中都找不到用户名时,我会遇到INTERNAL_SERVER_ERROR。

它说:

java.lang.NullPointerException
at com.pawnsoftware.User.authenticate(User.java:16)
at com.pawnsoftware.UserLoginServlet.doPost(UserLoginServlet.java:24)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)

等等...

您如何避免出现此错误?

错误在显示以下内容的行上:

if (user==null) {
    message = "Username not found.";
}

验证用户:

public static String authenticate(String username, String password) {
    String message;
    Entity user = UserUtil.findUserEntity(username);
    String pass = user.getProperty("password").toString();
    if (user==null) {
        message = "Username not found.";
    } else if (user!=null && !password.equals(pass)) {
        message = "Password is incorrect.";
    } else if (user!=null && password.equals(pass)) {
        message = "Successfully logged in!";
    } else {
        message = "Sorry, cannot find the username and password.";
    } 
    return message;
}

查找用户实体:

public static Entity findUserEntity (String username) {
    Key userKey = KeyFactory.createKey("User", username);
    try {
      return datastore.get(userKey);
    } catch (EntityNotFoundException e) {
      return null;
    }
}

认证更新:

public static String authenticate(String username, String password) {
    String message;
    Entity user = UserUtil.findUserEntity(username);
    password = encrypt(password);
    String pass = "";   
        try {
            pass = user.getProperty("password").toString();
        } catch (NullPointerException e) {
            message = "Username not found.";
        }
    if (user==null) {
        message = "Username not found.";
    } else if (user!=null && !password.equals(pass)) {
        message = "Password is incorrect.";
    } else if (user!=null && password.equals(pass)) {
        message = "Successfully logged in!";
    } else {
        message = "Sorry, cannot find the username and password.";
    } 
    return message;
}

如果use为null,则此行将失败:

String pass = user.getProperty("password").toString();

如果得到EntityNotFoundException并返回null则不显示。 反过来,这可能导致变量user出现NullPointerException

user.getProperty("password").toString();

您可以在此处添加保护声明:

if (user != null) {
   pass = user.getProperty("password").toString();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM