我有一个网络表单,允许用户输入信息并提交。如果用户在表单中提交了重复的 id 字段,则表单应该留在那里并提示错误信息。但是现在如果输入一些错误信息,页面将被重定向到显示“HTTP 状态 409 - 冲突”的错误页面。我的表格是:
<form action="/myapp/rest/customer/created" onsubmit="return checkForm();" method="POST">
<table border="1">
<tr>
<td>Customer name:</td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td>Customer ID:</td>
<td><input type="text" id="id" name="id"></td>
</tr>
<tr>
<td>Customer DOB:</td>
<td><input type="text" id="dob" name="dob"></td>
</tr>
</table>
<br/>
<input type="submit" value="Submit">
</form>
<div><span id="errorDiv" class="errorDiv" ></span></div>
JavaScript 函数checkForm()
是:
function checkForm() {
$.post("/myapp/rest/customer/created", function(data, status) {
if (status === "200") {
// redirect to destination
return true;
} else {
//display error information in the current form page
$("#errorDiv").html("<font color=red>ID already exists!</font>");
return false;
}
});
}
后端服务是 Java REST API,如果输入并提交了一些错误信息,它会捕获异常:
@Path("/customer")
public class CustomerService {
@Context UriInfo uriInfo;
@Context HttpServletRequest request;
@Context HttpServletResponse response;
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
CustomerJDBCTemplate dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("created")
public Response createCustomer(@FormParam("id") int id,
@FormParam("name") String name, @FormParam("dob") Date dob)
throws ServletException, IOException, WebApplicationException {
URI uri = URI.create(uriInfo.getPath());
Response r;
r = Response.created(uri).build();
try {
dbController.create(id, name, dob); //This may throw exception.
request.setAttribute("name", name);
request.setAttribute("dob", dob);
request.setAttribute("id", Integer.valueOf(id));
RequestDispatcher dispatcher = request.getRequestDispatcher("/confirm.jsp");
dispatcher.forward(request, response);
} catch (DataAccessException ex) {
throw new WebApplicationException(409);
}
return r;
}
}
那么,如果用户提交错误信息,为什么页面总是重定向到显示“HTTP Status 409 - Conflict”的错误页面?为什么 ajax 表单验证checkForm()
在这里不起作用?