我是新来的,整个晚上都在努力。我知道这应该很简单,我只是错过了一些愚蠢的东西。我有一个 jsp 页面和一个 servlet(下面的代码)。我正在尝试从我的数据库中搜索一个客户,这很有效。但是,如果找不到客户,我想在同一个 jsp 页面上发布一条错误消息,以便用户可以重新输入电话号码,以防他们犯了错误。我不确定如何做到这一点。我可以很好地转发到新的“客户”页面,并且我已成功尝试重定向回同一页面,但我不知道如何将消息放在那里。请帮忙!
jsp页面:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %>
<%@ page import="java.util.*" %>
<%@ include file="staticpages/pageHeader.html" %>
<br />
<hr />
<br />
<form name="custform" method="POST" action="ChooseCustomer.do" >
<span class="sectionheader">Look Up Customer by Phone Number:</span>
<input type="text" name="phone1" size="3" maxlength="3" onKeyUp="checklen(this)" />
<input type="text" name="phone2" size="3" maxlength="3" onKeyUp="checklen(this)" />
<input type="text" name="phone3" size="4" maxlength="4" onKeyUp="checklen(this)" />
<input type="submit" name="formaction" value="Search" />
<input type="submit" name="formaction" value="Enter New Customer" />
</form>
<%@ include file="staticpages/pageFooter.html" %>
小服务程序代码:
package pizzapkg;
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ChooseCustomer
*/
@WebServlet("/ChooseCustomer")
public class ChooseCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Customer c = null;
if (request.getParameter("formaction").equals("Search")) {
Database db = (Database) getServletContext().getAttribute("db");
/* Search Database for existing customer */
String searchPhone = request.getParameter("phone1")
+ request.getParameter("phone2")
+ request.getParameter("phone3");
String sql = "SELECT * FROM customers WHERE cust_phone=\"" + searchPhone + "\";";
ResultSet rs;
try {
rs = db.runSqlQuery(sql);
rs.next();
c = new Customer(rs.getString("cust_id"), rs.getString("cust_fname"),
rs.getString("cust_lname"), rs.getString("cust_address"),
rs.getString("cust_city"), rs.getString("cust_state"),
rs.getString("cust_zip"), rs.getString("cust_phone"),
rs.getString("cust_notes"));
} catch (Exception e) { e.printStackTrace(); }
request.setAttribute("customer", c);
}
RequestDispatcher rd = request.getRequestDispatcher("/customer.jsp");
rd.forward(request, response);
}
}
PS 这是我第一次构建 servlet,所以这对我来说是全新的。我喜欢示例,因此您可以提供的任何帮助将不胜感激。