0

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

2 回答 2

0

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

String pass = user.getProperty("password").toString();
于 2012-10-03T22:52:03.840 回答
0

如果你得到 aEntityNotFoundException和 return ,你不会显示null。反过来,这可能导致NullPointerException变量a user

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

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

if (user != null) {
   pass = user.getProperty("password").toString();
}
于 2012-10-03T22:55:42.110 回答