有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在尝试创建自己的身份验证。每次我尝试登录时,如果在GAE数据存储中找不到用户名,就会出现内部服务器错误

它说:

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;
}

共 (2) 个答案

  1. # 1 楼答案

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

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

    您可以在此处添加守卫声明:

    if (user != null) {
       pass = user.getProperty("password").toString();
    }
    
  2. # 2 楼答案

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

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