Iam尝试验证并插入数据。这里如果用户名存在于文件服务中,它应该发送错误消息,但在验证之后,它将被分派错误消息,并在文件服务中插入数据。我不知道代码失败的地方。
我的JSP:
<form name="create" id="myform" action="/create" method="post">
User Name: <input type="text" name="cliname"/>
<input type ="submit" value="submit"/>
</form>
我的Servlet:
public class CreateForm extends HttpServlet {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
String uname = req.getParameter("cliname");
Query query1 = new Query("Users");
List<Entity> cli_id = datastore.prepare(query1).asList(FetchOptions.Builder.withDefaults());
for (Entity client : cli_id){
username = (String)client.getProperty("User Name");
if(username.equals(uname)) {
RequestDispatcher rd = req.getRequestDispatcher("/Create.jsp");
req.setAttribute("errormsg", "User Name Already Exists");
rd.forward(req, resp);}}
Entity userInput = new Entity("Users");
userInput.setProperty("User Name", uname);
datastore.put(userInput);
}}
请建议我一个想法,
感谢您的帮助。
答案 0 :(得分:1)
我已更新您的代码。
public class CreateForm extends HttpServlet {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
String uname = req.getParameter("cliname");
Query query1 = new Query("Users");
List<Entity> cli_id = datastore.prepare(query1).asList(FetchOptions.Builder.withDefaults());
RequestDispatcher rd = null;
for (Entity client : cli_id){
username = (String)client.getProperty("User_Name");
if(username.equals(uname)) {
req.setAttribute("errormsg", "User Name Already Exists");
rd = req.getRequestDispatcher("/error.jsp");
}else{
Entity userInput = new Entity("Users");
userInput.setProperty("User_Name", uname);
datastore.put(userInput);
req.setAttribute("success", "User Name Added");
rd = req.getRequestDispatcher("/Create.jsp");
}
}
rd.forward(req, resp);
}
}