2

I have a simple servlet page that pushes to a jsp page, when you select the record you want, it is supposed to delete it from the database and reload the page. However what happens is in the console it prints the correct sql delete statement but it 1) it doesn't delete and 2) doesn't reload the page

Here is the servlet code

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


}

and the jsp page

<%@ 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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1393064
  • 401
  • 1
  • 16
  • 41

3 Answers3

0

Try changing

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

to

<input type="submit" value="Submit" name="Submit"/>
Russell Gutierrez
  • 1,372
  • 8
  • 19
0

Did you try using commit. If you won't commit the changes after the query is run, the changes won't be reflected in the database.

aa8y
  • 3,854
  • 4
  • 37
  • 62
  • I think you can use `int i = s.executeUpdate("COMMIT");` though I am not too sure. – aa8y Oct 08 '12 at 12:11
  • Also, try closing the Statement and Connection objects by adding a finally block after the last catch statement. This will ensure that they get closed even if the program encounters an exception in between. – aa8y Oct 08 '12 at 12:13
0

The problem is that the HTTP specification forbids redirection of DELETE / POST / PUT:

"10.3 Redirection 3xx

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. "


It is not clear why the database delete is not working, but it could be that you haven't committed the transaction. (OTOH, if the connection has auto-commit set, a commit won't be necessary.)

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216