简体   繁体   中英

Servlet not connecting to database

So I have a bookstore website. The pertinent code is as follows:

index.jsp (I have several blocks of the divs, where foo is a keyword for a book)

<form action="bookServlet" method="post">

            <div id='foo' style="float: left; width:25%">
                <img src ="${pageContext.request.contextPath}/images/foo.jpg" width ='200' height ='310' id ="foo" /> <br />
                Title of a Book <br />
                $7.99 <br />
                <input type= 'text' name= 'foo' size = 1 />
                <input type ='submit' name ='fooBtn' value ='Buy' onclick = 'this.disabled = true; return true;'/> <br /> <br />
            </div>

bookServlet.java (I have several blocks of the if statement, again one for each book)

public class bookServlet extends HttpServlet {

    public Statement statement;
    static boolean flag[] = {false, false, false, false, false, false, false, 
        false, false, false, false, false, false, false, false, false};


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException, SQLException {

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection connection = DriverManager.getConnection
                ("url exactly as my professor gave me", "username", "password");
            System.out.print("Connected");
            statement = connection.createStatement();
        }
        catch (Exception e){
            System.out.print("Could not connect");
        }
      if (request.getParameter("fooBtn") != null) {
         flag[0] = true;
         String queryString = "select stock from Inventory where title = 'foo'";
         ResultSet result = statement.executeQuery(queryString);
         int quantity = Integer.parseInt(request.getParameter("foo"));
         int stock = result.getInt(1);
         stock -= quantity;
         String insertString = "insert into Cart(title, items, price) values('foo', 1, 7.99)";
         statement.executeUpdate(insertString);
         String updateString = "update Inventory set stock = " + stock + " where title = 'foo'";
         statement.executeUpdate(updateString);
      }
    }
}

When I execute index.jsp, it displays correctly, but when I try to buy one of the books, it does not connect to the database, much less update it, or set the flag to true. I don't understand what I did wrong.

Edit: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>bookServlet</servlet-name>
        <servlet-class>books.bookServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>checkoutServlet</servlet-name>
        <servlet-class>books.checkoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>bookServlet</servlet-name>
        <url-pattern>/bookServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>checkoutServlet</servlet-name>
        <url-pattern>/checkoutServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Try changing processRequest to service .

A Servlet has 3 states:

  1. The servlet is initialized by calling init() method. This called only once.
  2. Then, the servlet calls service() method to process a client's request.
  3. The servlet is terminated by calling the destroy() method.

If the code you have shared is complete one. Then you are missing the service() method. You can handle the client request using doPost() and doGet() check them out.

I used Oracle database and I get connection object using this:

Connection conn = DriverManager.getConnection
  ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");

Check your url.

you can write your code in either of these three override function

@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
        throws ServletException, IOException {
    //your processRequest code
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //your processRequest code
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //your processRequest code
}

if you used service/doPost or doGet method to call processRequest method in servlet , it is well & good. But if you dont have , just creat it & call service processRequest method to get DB connection

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