简体   繁体   中英

error on servlet when opening a jsp

im having a problem with my servlet whenever it was open from my JSP which is ShowPurchasingItems.jsp it will not go to the next JSP.

here is my ShowPurchasingItems.jsp http://jsfiddle.net/0g3erumm/

and here is my Servlet that wont open my next 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");
           }    
       }    
    }
}

it would keep on catching error on this statment out.println("There is an error here"); and i am stuck in here i dont know what else is wrong with my program hope someone can help me.

You're committing a cardinal sin by swallowing the exception and thus losing all information that may help you get to the bottom of your problem!

You should change how your exceptions are handled, at the very least you should be dumping the stacktrace:

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

Once you have the stacktrace you'll be in a much better situation when it comes to diagnosing the problem (or asking more specific questions)!

Edit - Based on the exception posted in the comment:

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

Is being thrown because you are performing an update using the query method. You should change your code to this:

int updateCount = stmt.executeUpdate(query);

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

executeQuery executes the given SQL statement, which returns a single ResultSet object.

You're making INSERT, which doesn't return anything. I suppose that's why you're getting an exception.

I'd recommend to use PreparedStatement where you can bind variables and prevent SQL injection + some DB work faster with prepared statements, and executeUpdate instead of executeQuery

PreparedStatement stmt = null;
...

String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES (?, ?, ?, ?, ?)";

stmt = conn.prepareStatement(query);
stmt.setString(1, username);
...

int inserted = stmt.executeUpdate();

if (inserted > 0) {
// there was a successfull insert
...

There are a lot of examples on the Internet. For example: http://www.mkyong.com/jdbc/how-to-insert-date-value-in-preparedstatement/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM