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