[英]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.