我正在使用Jsp Ajax创建一个简单销售系统。当我添加数据时,单击添加按钮,所有HTML表数据已成功传递到我在控制台上看到的salesadd Servlet页面
我将数据以这种格式接收到Servlet Page
[{“ item”:“ Chocolate”,“ pro_price”:“ 32”,“ qty”:“ 1”,“ total”:“ 32”},
{“ item”:“ Mango”,“ pro_price”:“ 10”,“ qty”:“ 1”,“ total”:“ 10”}]
但是数据没有添加到数据库中,并显示这样的错误。我在下面写了完整错误。
此URL不支持HTTP方法GET
类型状态报告
此URL不支持messageHTTP方法GET
描述所请求的资源不允许使用指定的HTTP方法。
我现在尝试了以下附件,我认为是产品类别的问题
Product.java
public class Product
{
private String item;
private int price;
private int qty;
private int total;
public String getItem()
{
return item;
}
public void setItem(String item)
{
this.item = item;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
this.price = price;
}
public int getQty()
{
return qty;
}
public void setQty(int qty)
{
this.qty = qty;
}
public int getTotal()
{
return total;
}
public void setTotal(int total)
{
this.total = total;
}
}
Servlet页面
salesadd.java
@WebServlet("/salesadd")
public class salesadd extends HttpServlet {
Connection con;
PreparedStatement pst;
int row;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
Connection con;
PreparedStatement pst;
String jsonData = request.getParameter("data1");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
Product data1 = gson.fromJson(jsonData, Product.class);
String item = data1.getItem();
int price = data1.getPrice();
int qty = data1.getQty();
int total = data1.getTotal();
try
{
con = DriverManager.getConnection("jdbc:mysql://localhost/icepos", "root", "");
pst = con.prepareStatement("insert into sale_product(item,price,qty,total)values(?,?,?,?) ");
pst.setString(1, data1.getItem());
pst.setInt(2, data1.getPrice());
pst.setInt(3, data1.getQty());
pst.setInt(4, data1.getTotal());
pst.executeUpdate();
out.println("<font color='green'> Record Adddd </font>");
} catch (SQLException ex) {
out.println("<font color='red'> Record Failed </font>");
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rsp ) throws IOException,ServletException
{
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
out.println("<font color='green'> Record Adddd </font>");
}
最佳答案
您可以循环列表,如下所示:
for (Product product : objectList) {
try
{
con = DriverManager.getConnection("jdbc:mysql://localhost/icepos", "root", "");
pst = con.prepareStatement("insert into sale_product(item,price,qty,total)values(?,?,?,?) ");
pst.setString(1, product.getItem());
pst.setInt(2, product.getPrice());
pst.setInt(3, product.getQty());
pst.setInt(4, product.getTotal());
pst.executeUpdate();
out.println("<font color='green'> Record Adddd </font>");
} catch (SQLException ex) {
out.println("<font color='red'> Record Failed </font>");
}
}