通过Ajax向Servlet发送请求(非春季)

时间:2018-11-15 18:32:42

标签: java ajax servlets

我有一个列出了一系列产品的CRUD表,我需要的是当我单击按钮时,Ajax会自动向Servlet发送一个请求,告诉它我要更改状态(而不是删除产品) )添加到数据库中,然后重新加载表。

我已经完成了大部分代码,这是我所拥有的AJAX(我想这是错误的部分),我正在尝试使其在单击行时正常工作,因此请忽略该部分的每一行都有一个删除按钮。

       <script>
                        $("#test").on('click','tr',function() {
                            var id = $(this).find("td:first-child").text();
                            console.log(id);
                            $.ajax({
                            url: "statecontroller.do",
                            type: 'POST',
                            data: { id : id},
                            success: function() {
                            }
                          });
                        });
    </script> 

这是servlet代码:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));  
            ProductDAO productBD = new ProductDAO();
            Product products = productBD.selectById(id);
            if(products.getState() == "Active"){
                    Product product = new Product(id,"Not Active");
                    productBD.update(product);
                    ArrayList<Product> productList = new ArrayList<>();
                    productList = productBD.selectAll();
                    request.getSession().setAttribute("productList", productList);
                    request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
                }else if(products.getState() == "Not Active"){
                    Product product = new Product(id,"Active");
                    productBD.update(product);
                    ArrayList<Product> productList = new ArrayList<>();
                    productList = productBD.selectAll();
                    request.getSession().setAttribute("productList", productList);
                    request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
                }

}

我尝试查找它,但是只发现如何使用Spring

(这是完整的servlet代码,上面有西班牙语名称,这就是我为原始帖子翻译的原因):

package controladores;

import daos.ClienteDAO;
import dtos.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author lycan
 */
@WebServlet(name = "ControladorEstado", urlPatterns = {"/controladorestado.do"})
public class ControladorEstado extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));  
            ClienteDAO clientebd = new ClienteDAO();
            Cliente clientes = clientebd.selectById(id);
            if(clientes.getEstado() == "Activo"){
                    Cliente cliente = new Cliente(id,"No Activo");
                    clientebd.update(cliente);
                    ArrayList<Cliente> lista = new ArrayList<>();
                        lista = clientebd.selectAll();
                        request.getSession().setAttribute("lista", lista);
                        request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
                }else if(clientes.getEstado() == "No Activo"){
                    Cliente cliente = new Cliente(id,"Activo");
                    clientebd.update(cliente);
                    ArrayList<Cliente> lista = new ArrayList<>();
                        lista = clientebd.selectAll();
                        request.getSession().setAttribute("lista", lista);
                        request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
                }

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

这是上市代码:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- 
    Document   : listar
    Created on : 19-oct-2018, 11:00:29
    Author     : lycan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <%@include  file="../WEB-INF/jspf/estilos.jspf"%>
        <title>Sistema Ventas</title>
    </head>
    <body>
        <div class="container-fluid">
            <%@include  file="../WEB-INF/jspf/header.jspf"%>
            <%@include  file="../WEB-INF/jspf/nav.jspf"%>
            <section>
                <table id="test" class="table table-bordered">
                    <thead class="thead-dark">
                        <tr>
                            <th>ID</th>
                            <th>Nombre</th>
                            <th>Descripcion</th>
                            <th>Categoria</th>
                            <th>Estado</th>
                            <th><i class="fas fa-binoculars"></i></th>
                            <th><i class="fas fa-pen-alt"></i></th>
                            <th><i class="fas fa-user-times"></i></th>
                        </tr>
                    </thead>
                    <tbody>
                    <c:forEach var="clientes" items="${sessionScope.lista}">
                     <tr>
                            <td>${clientes.id}</td>
                            <td>${clientes.nombre}</td>
                            <td>${clientes.descripcion}</td>
                            <td>${clientes.categoria}</td>
                            <td>${clientes.estado}</td>
                            <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
                            <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
                            <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
                        </tr>
                    </c:forEach>  

                    </tbody>
                </table>
            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=crear" class="btn btn-primary btn-lg " role="button">Registrar</a>
            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=buscar" class="btn btn-primary btn-lg " role="button">Buscar</a>    
            </section>   
            <%@include  file="../WEB-INF/jspf/footer.jspf"%> 
        </div>        
        <%@include  file="../WEB-INF/jspf/js.jspf"%>
        <script>
                            $("#test").on('click','tr',function() {
                                var id = $(this).find("td:first-child").text();
                                console.log(id);
                                $.ajax({
                                url: "controladorestado.do",
                                type: 'POST',
                                data: { id : id},
                                success: function() {
                                }
                              });
                                 // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                            });
        </script> 
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

好的,我知道您现在在做什么,感谢您提供了更多信息。什么也没发生的原因是因为在您的servlet中,您试图返回进行ajax调用的页面。 (而且您甚至都无法处理响应)

从外观上看,您想通过ajax方法返回一个表,但是为此,您需要创建一个单独的jsp,然后将其返回。例如:

/wcliente/内创建一个称为用户表的新jsp

user-table.jsp

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
       <table class="table table-bordered">
                <thead class="thead-dark">
                    <tr>
                        <th>ID</th>
                        <th>Nombre</th>
                        <th>Descripcion</th>
                        <th>Categoria</th>
                        <th>Estado</th>
                        <th><i class="fas fa-binoculars"></i></th>
                        <th><i class="fas fa-pen-alt"></i></th>
                        <th><i class="fas fa-user-times"></i></th>
                    </tr>
                </thead>
                <tbody>
                <c:forEach var="clientes" items="${lista}">
                 <tr>
                        <td>${clientes.id}</td>
                        <td>${clientes.nombre}</td>
                        <td>${clientes.descripcion}</td>
                        <td>${clientes.categoria}</td>
                        <td>${clientes.estado}</td>
                        <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
                        <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
                        <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
                    </tr>
                </c:forEach>  

                </tbody>
            </table>
</data>

现在在您的servlet中,而不是这个:

request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);

执行此操作:

request.getRequestDispatcher("/wcliente/user-table.jsp").forward(request, response);

对于listar.jsp中的ajax,请改为执行以下操作:

<script>

$("#test").on('click','tr',function() {  
 var id = $(this).find("td:first-child").text();

    $.post("controladorestado.do", {id : id}, function(responseXml) {                // Execute Ajax POST request on URL of "controladorestado.do" and execute the following function with Ajax response XML...
        $("#test").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "test".
    });
});

 </script>

参考: How to use Servlets and Ajax?