[英]Authenticating with GAE Datastore return null on Entity User
I'm trying to create my own authentication. 我正在尝试创建自己的身份验证。 Everytime I try to login, and the username is not found in the GAE datastore, I get to have INTERNAL_SERVER_ERROR.
每次尝试登录时,在GAE数据存储区中都找不到用户名时,我会遇到INTERNAL_SERVER_ERROR。
It says that: 它说:
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)
and so on... 等等...
How do you avoid having this error? 您如何避免出现此错误?
The error is on the line that says: 错误在显示以下内容的行上:
if (user==null) {
message = "Username not found.";
}
Authenticate User: 验证用户:
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;
}
Find User Entity: 查找用户实体:
public static Entity findUserEntity (String username) {
Key userKey = KeyFactory.createKey("User", username);
try {
return datastore.get(userKey);
} catch (EntityNotFoundException e) {
return null;
}
}
Update on authentication: 认证更新:
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();
You don't display if you get get a EntityNotFoundException
and return null
. 如果得到
EntityNotFoundException
并返回null
则不显示。 This, in turn, can cause a NullPointerException
for the variable user
: 反过来,这可能导致变量
user
出现NullPointerException
:
user.getProperty("password").toString();
You could add a guard statement here: 您可以在此处添加保护声明:
if (user != null) {
pass = user.getProperty("password").toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.