这里的第一个问题。在JSP页面中,我有一个表单。我想要做的是询问servlet是否该表单的输入值已经存在于我的mysql数据库中。我正在使用2个不同的Servlet。 “ServletInsert”将数据插入mysql数据库。 “ServletCheck”检查mysql数据库中是否存在票证ID。票证ID无法自动生成。
JSP页面:
<form id="myForm" action="ServletInsert" method="post">
<div>
<label>Ticket Id:</label>
<input type="text" name="id"/>
</div>
<input type="submit" name="submit" value="Send" />
</form>
<script>
$('#myForm').submit(function() {
/** <<SEND INPUT VALUE("id") TO SERVLET("ServletCheck")>> */
if ("the answer from the servlet is true"){
return true;
}else if ("the answer from the servlet is false")
return false;
alert("ticket id already exists");
}
});
</script>
Servlet(“ServletCheck”):
package Servlets;
import Entity.Ticket;
public class ServletCheck extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
processRequest(request, response);
String id = request.getParameter("id"); /**the input value*/
ArrayList<Ticket> list = new ArrayList<Ticket>();
list = ListOfTicketsDB(); /**this procedure gets the list of tickets from
the mysql database (already know how to do that)*/
boolean b = existsOnList(list, id);
/**The answer doesn't have to be boolean. It can be a String("True","False")*/
/**<<SEND THE ANSWER TO THE JSP PAGE>>*/
}
/**checks if the value is inside the array*/
boolean existsOnList(ArrayList<Ticket> list, String id) {
for (Ticket T : list) {
if (T.getID_TICKET().equals(id)) {
return true;
}
}
return false;
}
}
答案 0 :(得分:0)
要完成此操作,您需要包含以下内容:
/**<<SEND THE ANSWER TO THE JSP PAGE>>*/
response.setContentType("application/text");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
if(existsOnList(list, id)){
out.write("False");
}else{
out.write("True");
}
然后在你的JSP上,你会想要(使用AJAX):
$('#myForm').submit(function(e) {
$.get('ServletCheck', $('#myForm').serialize(), function (response) {
if (response === "True"){
return true;
}else if (response === "False"){
e.preventDefault(); //cancel form submission
return false;
alert("ticket id already exists");
}
}
});