Intercambio de objetos y colecciones mediante AJAX y XML en aplicaciones Java EE

En el desarrollo web con Java EE, es común necesitar recuperar datos del servdior de forma asíncrona. A continuación, se detalla cómo transmitir un objeto individual y, posteriormente, una colección de objetos desde un Servlet hacia el cliente utilizando XML y jQuery.

Transmisión de un objeto individual

Para enviar una única entidad, el servidor construye una respuesta XML estructurada. En este ejemplo, utilizaremos datos de un producto para ilustrar el concepto.

Implementación en el Servlet

package com.ejemplo.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ObtenerProducto")
public class ProductoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("text/xml;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        
        // Simulación de obtención de datos de una base de datos
        String nombreProducto = "Laptop Pro";
        double precioProducto = 1299.99;
        int stockProducto = 45;
        
        PrintWriter out = response.getWriter();
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.println("<producto>");
        out.println("  <nombre>" + nombreProducto + "</nombre>");
        out.println("  <precio>" + precioProducto + "</precio>");
        out.println("  <stock>" + stockProducto + "</stock>");
        out.println("</producto>");
    }

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

Consumo en el cliente (JSP)

El lado del cliente realiza la petición AJAX y parsea el documento XML para extraer los valores y renderizarlos en el DOM.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<html>
<head>
    <meta charset="UTF-8">
    <title>Detalle de Producto</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#btnCargar").on("click", function() {
                $.ajax({
                    url: "ObtenerProducto",
                    type: "GET",
                    dataType: "xml",
                    success: function(xmlData) {
                        var nombre = $(xmlData).find("nombre").text();
                        var precio = $(xmlData).find("precio").text();
                        var stock = $(xmlData).find("stock").text();
                        
                        var lista = $("#detalles");
                        lista.empty();
                        lista.append("<li>Nombre: " + nombre + "</li>");
                        lista.append("<li>Precio: $" + precio + "</li>");
                        lista.append("<li>Stock: " + stock + " unidades</li>");
                    },
                    error: function() {
                        alert("Error al cargar los datos.");
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btnCargar">Cargar Producto</button>
    <ul id="detalles"></ul>
</body>
</html>

Transmisión de colecciones o arrays

Cuendo se requiere enviar múltiples registros, la estructura XML debe envolver cada elemento dentro de un nodo raíz, permitiendo que el cliente itere sobre los resultados.

Implementación en el Servlet

package com.ejemplo.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ListarProductos")
public class ListaProductosServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("text/xml;charset=UTF-8");
        
        // Simulación de lista de objetos
        List<String[]> productos = Arrays.asList(
            new String[]{"101", "Teclado Mecánico", "89.50"},
            new String[]{"102", "Ratón Inalámbrico", "45.00"},
            new String[]{"103", "Monitor 4K", "320.00"}
        );
        
        PrintWriter out = response.getWriter();
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.println("<catalogo>");
        
        for (String[] prod : productos) {
            out.println("  <item id=\"" + prod[0] + "\">");
            out.println("    <nombre>" + prod[1] + "</nombre>");
            out.println("    <precio>" + prod[2] + "</precio>");
            out.println("  </item>");
        }
        
        out.println("</catalogo>");
    }

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

Consumo en el cliente (JSP)

En el front end, utilizamos un bucle para recorrer cada nodo devuelto en el XML y construimos dinámicamente las filas de una tabla HTML.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<html>
<head>
    <meta charset="UTF-8">
    <title>Catálogo de Productos</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#btnListar").on("click", function() {
                $.ajax({
                    url: "ListarProductos",
                    type: "GET",
                    dataType: "xml",
                    success: function(xmlData) {
                        var items = $(xmlData).find("item");
                        var tabla = $("#tablaCatalogo tbody");
                        tabla.empty();
                        
                        items.each(function() {
                            var id = $(this).attr("id");
                            var nombre = $(this).find("nombre").text();
                            var precio = $(this).find("precio").text();
                            
                            var fila = "<tr>" +
                                       "<td>" + id + "</td>" +
                                       "<td>" + nombre + "</td>" +
                                       "<td>$" + precio + "</td>" +
                                       "</tr>";
                            tabla.append(fila);
                        });
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btnListar">Cargar Catálogo</button>
    <table id="tablaCatalogo" border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>Producto</th>
                <th>Precio</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</body>
</html>

Etiquetas: Java EE Servlets jsp AJAX jQuery

Publicado el 6-9 04:59