1
問題是當我點擊按鈕刪除在userNotes.jsp測試函數在deleteData - out.println(value)
,工作 - 它顯示了我點擊按鈕的當前值,但沒有任何東西其他。它不會從數據庫中刪除數據,也不會在響應中發送重定向,我需要做什麼?
userNotes.jsp使用jsp從數據庫刪除行
<table id="notes" border="2">
<tr>
<td>note name</td>
<td>note</td>
</tr>
<%
PrintWriter writer = response.getWriter();
int id = Integer.parseInt(request.getParameter("r"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/evernoteDB",
"evernoteDB", "0633739768z");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("SELECT * FROM note");
while (rs.next())
{
%>
<tr>
<td><%=rs.getString(1) %></td>
<td><%=rs.getString(2) %></td>
<td>
<a href=deleteData?id=<%=rs.getString(1) %>> Delete </a>
</td>
</tr>
<%
}
rs.close();
st.close();
con.close();
}
catch(ClassNotFoundException e)
{
writer.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e)
{
writer.println("SQLException caught: " + e.getMessage());
}
catch (Exception e)
{
writer.println(e);
}
%>
</table>
deleteData - servlet的
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.*;
import java.sql.*;
@WebServlet("/deleteData")
public class deleteData extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = request.getParameter("id");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/evernoteDB",
"evernoteDB", "0633739768z");
Statement st = conn.createStatement();
st.executeUpdate("DELETE FROM note WHERE noteName=" + value);
out.print(value);
response.sendRedirect("http://localhost:8080/userNotes.jsp");
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
保持你的業務邏輯的Java類/ EJB和只使用JSP中的視圖層 –
從技術上講,你可以做到這一點,我們甚至可以與上面的代碼解決問題。但是,原則上,我不適合從JSP訪問數據庫。因爲數據庫屬於服務器端,所以數據庫操作應該在網頁上執行。 – Alp