2

我有一个简单的 servlet 页面,它推送到一个 jsp 页面,当你选择你想要的记录时,它应该从数据库中删除它并重新加载页面。然而发生的事情是在控制台中它打印正确的 sql delete 语句,但它1)它不删除和 2)不重新加载页面

这是servlet代码

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;


/**
 * Servlet implementation class StudentModify
 */
@WebServlet("/StudentModify")
public class StudentModify extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentModify() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        sendBack(request, response);
    }

    private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);

        //Set data you want to send back to the request (will be forwarded to the page)
        //Can set string, int, list, array etc.
        String sql = "SELECT ul.id, s.name, l.time, l.day, l.room,l.id" +
              " FROM lab l, subject s, user_lab ul" +
                " WHERE ul.user_id=" + (Integer)session.getAttribute("id") +" AND ul.lab_id ="+ "l.id"+" AND l.subject_id ="+"s.id";

      try{
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
        System.out.println("got boob");
        System.out.println(session.getAttribute("id"));

          Statement stmt = con.createStatement();
          ResultSet res = stmt.executeQuery(sql);
          System.out.println(res);
          ArrayList<String> list1 = new ArrayList<String>();
          ArrayList<String> list2 = new ArrayList<String>();
          ArrayList<String> list3 = new ArrayList<String>();
          if (res.next()){
              do{
                  list1.add(res.getString(1));
                   list2.add(res.getString(2) + " " + res.getString(3) +" "+ res.getString(4) +" "+res.getString(5));
                   list3.add(res.getString(6));

              }while(res.next());

          String[] arr = list1.toArray(new String[list1.size()]);
          String[] arr1 = list2.toArray(new String[list2.size()]);
          String[] arr2 = list3.toArray(new String[list3.size()]);
          request.setAttribute("res", arr);
          request.setAttribute("res1", arr1);
          request.setAttribute("res2", arr2);
          }



      }catch (SQLException e) {
        } 
        catch (Exception e) {
        } 


        //Decides what page to send the request data to
        RequestDispatcher view = request.getRequestDispatcher("StudentModify.jsp");
        //Forward to the page and pass the request and response information
        view.forward(request, response); 
    } 



    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession(true);
        int user_id = Integer.parseInt((String)request.getParameter("user_id"));
        int lab_id =  Integer.parseInt((String)request.getParameter("lab_id"));
        int id = Integer.parseInt((String)request.getParameter("id"));
        System.out.println(request.getParameter("user_id")+"  "+request.getParameter("lab_id"));
          String message = null; 
          try {
              Class.forName("com.mysql.jdbc.Driver");
              Connection con = 
                DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
            System.out.println("got connection"); 
            Statement s = con.createStatement(); 

            String sql = "DELETE FROM user_lab" + 
                      " WHERE id= " + id + " AND user_id= " + user_id + " AND lab_id= " + lab_id; 

              System.out.println(sql);
              int i = s.executeUpdate(sql); 
              if (i==1) {
                message = "Successfully Enrolled In lab."; 
                response.sendRedirect("Student_manage.jsp");
              } 

              s.close(); 
              con.close(); 
            } 
            catch (SQLException e) {
              message = "Error." + e.toString(); 
            } 
            catch (Exception e) {
              message = "Error." + e.toString(); 
            } 
            if (message!=null) {
              PrintWriter out = response.getWriter(); 
              out.println("<B>" + message + "</B><BR>"); 
              out.println("<HR><BR>"); 
            } 

          } 
// TODO Auto-generated method stub


}

和jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Mars University Lab System</title>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>

<body>
<jsp:include page="headerStudent.jsp"/>
<tr>
<td>
</td>
</tr>
<tr>
<td>

<div id = "centrecontent">
<br>
<h3>Enrol into Labs</h3>

<% if (session.getAttribute("id") == null) {
   System.out.println("error");
}
else{ %>
<%  String[] list1 = (String[])request.getAttribute("res");
String[] list2 = (String[])request.getAttribute("res1");
String[] list3 = (String[])request.getAttribute("res2");%>

<p>Please Choose a Class</p>

<form name="StudentModify" ACTION="StudentModify" method="post">


        <%
        for(int i=0; i<list1.length; i++)  
        { %> 
        <input type="hidden" name="id" value=<%=list3[i]%>>
        <input type="hidden" name="user_id" value=<%=session.getAttribute("id")%>>  
        <%out.print(list2[i] + " ");%>
        <input type="radio" name="lab_id" value=<%out.println(list1[i]);%>><br>
        <%
        } 
            }
            %>

        <input type=SUBMIT value="Submit" name="Submit"/>
        </form>


</div>
<jsp:include page="footer.jsp"/>


</body>

</html>
4

3 回答 3

0

您是否尝试过使用提交。如果您在查询运行后不提交更改,则更改不会反映在数据库中。

于 2012-10-08T10:21:07.363 回答
0

问题是HTTP规范禁止DELETE / POST / PUT的重定向:

"10.3 重定向 3xx

此类状态码表明用户代理需要采取进一步的行动才能满足请求。当且仅当第二个请求中使用的方法是 GET 或 HEAD 时,用户代理可以执行所需的操作,而无需与用户交互。"


目前尚不清楚为什么数据库删除不起作用,但可能是您尚未提交事务。(OTOH,如果连接设置了自动提交,则不需要提交。)

于 2012-10-08T10:22:20.937 回答
0

Try changing

<input type=SUBMIT value="Submit" name="Submit"/>

to

<input type="submit" value="Submit" name="Submit"/>
于 2012-10-08T10:14:03.407 回答