所以我有一個書店網站。相關代碼如下:Servlet未連接到數據庫
的index.jsp(I具有的div,其中,foo是一本書的關鍵詞的幾個塊)
<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具有幾個每本書的if語句,再一個塊)
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);
}
}
}
當我執行的index.jsp,它正確地顯示,但是當我試圖購買的一本書,它不連接到數據庫,更不用說更新它,或將標誌設置爲true。我不明白我做錯了什麼。
編輯: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>
添加'e.printStackTrace()'到你的catch塊。永遠不要忽視一個例外。 –
你得到「無法連接」輸出嗎? –
我沒有得到任何輸出。它甚至沒有嘗試連接。 – user2302019