我正在尝试创建自己的身份验证。每次我尝试登录,并且在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;
}
答案 0 :(得分:0)
如果use为null,则此行将失败:
String pass = user.getProperty("password").toString();
答案 1 :(得分:0)
如果您获得EntityNotFoundException
并返回null
,则不会显示。反过来,这可能会导致变量NullPointerException
的{{1}}:
user
你可以在这里添加一个警卫声明:
user.getProperty("password").toString();