简体   繁体   English

Java Servlet删除不重定向

[英]java servlet delete not redirecting

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. 我有一个简单的servlet页面,可推送到一个jsp页面,当您选择所需的记录时,应该将其从数据库中删除并重新加载该页面。 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 但是,发生的情况是在控制台中它打印了正确的sql delete语句,但是它1)不会删除,并且2)不会重新加载页面

Here is the servlet code 这是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


}

and the jsp page 和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>

Try changing 尝试改变

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

to

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

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. 如果您在查询运行后不提交更改,则更改将不会反映在数据库中。

The problem is that the HTTP specification forbids redirection of DELETE / POST / PUT: 问题是HTTP规范禁止重定向DELETE / POST / PUT:

"10.3 Redirection 3xx “ 10.3重定向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. 当且仅当第二个请求中使用的方法是GET或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.) (OTOH,如果连接设置了自动提交,则无需提交。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM