我试图在我的servlet中使用doPost()方法将JSP表单中的值插入到数据库中,但是它似乎没有工作,我想知道如果有人在这里可以帮助我谢谢。这是以下代码:
public boolean addOrder(Connection conn) {
boolean success = false;
// Declare JDBC objects
PreparedStatement ps = null;
try {
String sql = "INSERT INTO OrderInfo(SizeOfPizza, NumOfToppings, Quantity, "
+ " Delivery, Price) VALUES(?, ?, ?, ?, ?);";
ps = conn.prepareStatement(sql);
ps.setString(1, order.getPizzaSize());
ps.setInt(2, order.getNumToppings());
ps.setInt(3, order.getQuantity());
ps.setBoolean(4, order.isDelivery());
ps.setDouble(5, order.getPrice());
int count = ps.executeUpdate();
if (count > 0) {
success = true;
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
} finally {
DBConnection.closeJDBCObjects(conn, ps);
return success;
}
}
要插入数据库的Servlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OrderDAO dao = new OrderDAO();
DBConnection conn = (DBConnection)this.getServletContext().getAttribute("dbConn");
boolean ordersuccess = dao.addOrder(conn.getConnection());
HttpSession session = request.getSession();
session.setAttribute("ordersuccess", ordersuccess);
request.getRequestDispatcher("ReceiptPage.jsp").forward(request, response);
}
页面填写表单并发送到servlet
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pizza Order Page</title>
<%
String fname = request.getParameter("firstName");
String lname = request.getParameter("lastName");
%>
<style>
body{
background-color: silver;
}
#title{
background-color: gray;
}
</style>
</head>
<body>
<h1 id="title" align="center">Hello <%out.print(fname + " " + lname);%></h1>
<p>Please fill out your order information</p>
<p><b>Delivery Options</b></p>
<form action="ReceiptServlet.do" method="POST">
<Select name="deliveryOption">
<option value="Pick Up">Pick Up</option>
<option value="Delivery">Delivery</option>
</Select>
<br>
<p><b>Size Options</b></p>
<input type="radio" name="size" value="Small">Regular ($5.00)<br><br>
<input type="radio" name="size" value="Large">Large ($7.00)
<br>
<p><b>Topping Choices</b></p>
<input type="radio" value="Pepperoni" name="topping">Pepperoni ($1.00)</option><br>
<input type="radio" value="Mushroom" name="topping">Mushroom ($1.00)</option><br>
<input type="radio" value="Olives" name="topping">Olives ($1.00)</option><br>
<input type="radio" value="Sausage" name="topping">Sausage ($1.00)</option><br>
<input type="radio" value="Pineapple" name="topping">Pineapple ($1.00)</option><br>
<br>
<p><b>Enter the amount of pizzas you would like to order</b></p>
<input type="text" name="pizzaQty">
<br><br>
<input type="submit" value="Place Order">
</form>
</body>