使用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;
}
# 1 楼答案
如果得到一个
EntityNotFoundException
并返回null
,则不显示。这反过来会导致变量user
出现NullPointerException
:您可以在此处添加守卫声明:
# 2 楼答案
如果use为null,则此行将失败: