gpt4 book ai didi

java - 打开jsp时servlet出错

转载 作者:行者123 更新时间:2023-11-29 05:14:54 25 4
gpt4 key购买 nike

每当我的 servlet 从我的 ShowPurchasingItems.jsp 打开时,我的 servlet 就会出现问题,它不会转到下一个 JSP。

这是我的 ShowPurchasingItems.jsp http://jsfiddle.net/0g3erumm/

这是我的 Servlet,它不会打开我的下一个 JSP

 package connection;

import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

@WebServlet("/CheckOutServlet")
public class CheckOutServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

String User = (String) session.getAttribute("username");
String id = (String) session.getAttribute("stockIdToPurchase");
float price = (float) session.getAttribute("UnitPriceToPurchase");
int stock = (int) session.getAttribute("OnStockToPurchase");
int quantityOrdered = (int) session.getAttribute("purchaseQuantity");
float totalPrice = price * quantityOrdered;
int newStock = stock - quantityOrdered;

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String url = "jdbc:mysql://localhost:3306/inventory";
String user = "root";
String password = "password";
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES ('"+User+"', '"+id+"', "+price+", "+quantityOrdered+", "+totalPrice+");";

try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);

if(rs.next())
{
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
}

catch(Exception e)
{
out.println("There is an error here");
}

finally
{
out.close();
try
{
rs.close();
stmt.close();
conn.close();
}

catch (Exception e)
{
out.println("There is no error here");
}
}
}
}

它会继续捕获这个语句的错误 out.println("There is an error here");我被困在这里我不知道我的程序还有什么问题希望有人能帮助我。

最佳答案

吞下异常并因此丢失所有可能帮助您查明问题根源的信息是犯了大罪!

你应该改变你的异常处理方式,至少你应该转储堆栈跟踪:

catch(Exception e) {
out.println("There is an error here");
e.printStackTrace();
}

一旦你有了堆栈跟踪,你就会在诊断问题(或提出更具体的问题)时处于更好的状态!

编辑 - 基于评论中发布的异常:

java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

被抛出是因为您正在使用 query 方法执行 update。您应该将代码更改为:

int updateCount = stmt.executeUpdate(query);

if(updateCount > 0) {
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}

关于java - 打开jsp时servlet出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26947148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com