我是servlets和app引擎数据存储的新手。我尝试使用servlet创建一个简单的登录和注册表单,并将新用户从注册表单servlet存储在app引擎数据存储中。 但我不知道如何检查用户在登录时提供的用户名和密码是否与数据存储条目匹配。任何人都可以帮助我吗?
登录Servlet:
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String user = req.getParameter("usern");
String password = req.getParameter("psd");
HttpSession s = req.getSession();
s.setAttribute("usernm", user);
if ((user.equalsIgnoreCase(????) && password.equalsIgnoreCase(????))) {
req.getRequestDispatcher("/profile").include(req, res);
} else {
out.print("Sorry UserName or Password Error!");
req.getRequestDispatcher("/index.html").forward(req, res);
}
}
注册Servlet:
public class RegistrationServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String n = req.getParameter("userName");
String p = req.getParameter("userPass");
String c = req.getParameter("confirmPass");
String e = req.getParameter("userEmail");
if (!c.equals(p)) {
out.println("<h3>Enter correct password</h3>");
req.getRequestDispatcher("register.html").forward(req, res);
} else {
Entity u = new Entity("User", e);
u.setProperty("userName", n);
u.setProperty("passWord", p);
u.setProperty("userEmail", e);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(u);
u.getKey().getName();
com.google.appengine.api.datastore.Key k = KeyFactory.createKey("User", e);
out.println("<h3>Successfully registered</h3>");
}
}
}
答案 0 :(得分:0)
您可以使用用户的用户名检查用户实体,然后检查给定的密码是否与用户的密码匹配:
String user = req.getParameter("usern");
String password = req.getParameter("psd");
Query q = new Query("User")
.setFilter(new FilterPredicate("userName", FilterOperator.EQUAL, user));
PreparedQuery pq = datastore.prepare(q);
Entity storedUser = pq.asSingleEntity();
String storedPassword = (String) storedUser.getProperty("passWord");
if (storedPassword.equals(password)) {
//correct password
}
您可以在documentation
中找到有关使用Google Cloud Datastore的更多信息