【问题标题】:Authenticating with GAE Datastore return null on Entity User使用 GAE 数据存储进行身份验证在实体用户上返回 null
【发布时间】:2012-10-03 22:49:54
【问题描述】:

我正在尝试创建自己的身份验证。每次我尝试登录,并且在 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;
}

【问题讨论】:

    标签: java google-app-engine google-cloud-datastore


    【解决方案1】:

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

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

    您可以在此处添加保护语句:

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

    【讨论】:

    • 感谢 NullPointerException 提示。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2014-05-28
      • 2019-12-17
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      相关资源
      最近更新 更多