0% encontró este documento útil (0 votos)
34 vistas4 páginas

Servlet

Este documento describe tres servlets Java que gestionan operaciones CRUD sobre una base de datos de productos utilizando JDBC: un servlet guarda productos, otro los elimina y el último los muestra en una tabla HTML.

Cargado por

jessperez272
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como TXT, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
34 vistas4 páginas

Servlet

Este documento describe tres servlets Java que gestionan operaciones CRUD sobre una base de datos de productos utilizando JDBC: un servlet guarda productos, otro los elimina y el último los muestra en una tabla HTML.

Cargado por

jessperez272
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como TXT, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 4

***servlet***

*** GuardarProductoServlet. java***


***********************************

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import jakarta.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
*
* @author
*/

@WebServlet(name = "GuardarProductoServlet", urlPatterns =


{"/guardar_producto"})
public class GuardarProductoServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
// Recuperar los parámetros del formulario
String nombre = request.getParameter("nombre");
String descripcion = request.getParameter("descripcion");
double precio = Double.parseDouble(request.getParameter("precio"));
int stock = Integer.parseInt(request.getParameter("stock"));

// Establecer la conexión a la base de datos


Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/productos_db?
serverTimezone=UTC", "root", "123456");

// Crear la consulta SQL para insertar el producto


String sql = "INSERT INTO productos (nombre, descripcion, precio,
stock) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, nombre);
stmt.setString(2, descripcion);
stmt.setDouble(3, precio);
stmt.setInt(4, stock);

// Ejecutar la consulta
int filasAfectadas = stmt.executeUpdate();
if (filasAfectadas > 0) {
out.println("<h1>Producto guardado correctamente</h1>");
} else {
out.println("<h1>Ocurrió un error al guardar el
producto</h1>");
}
} catch (ClassNotFoundException | SQLException ex) {
out.println("<h1>Error de base de datos: " + ex.getMessage() +
"</h1>");
} finally {
// Cerrar la conexión y liberar recursos
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
out.println("<h1>Error al cerrar la conexión: " +
ex.getMessage() + "</h1>");
}
}
}
}
}

**** eliminar_producto.java****
*******************************

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
*
* @author
*/
@WebServlet(name = "eliminar_producto", urlPatterns = {"/eliminar_producto"})
public class eliminar_producto extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
// Recuperar el ID del producto a eliminar
int id = Integer.parseInt(request.getParameter("id"));

// Establecer la conexión a la base de datos


Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/productos_db?
serverTimezone=UTC", "root", "123456");

// Crear la consulta SQL para eliminar el producto


String sql = "DELETE FROM productos WHERE id = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);

// Ejecutar la consulta
int filasAfectadas = stmt.executeUpdate();
if (filasAfectadas > 0) {
out.println("<h1>Producto eliminado correctamente</h1>");
} else {
out.println("<h1>No se encontró ningún producto con ese
ID</h1>");
}
} catch (ClassNotFoundException | SQLException ex) {
out.println("<h1>Error de base de datos: " + ex.getMessage() +
"</h1>");
} finally {
// Cerrar la conexión y liberar recursos
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
out.println("<h1>Error al cerrar la conexión: " +
ex.getMessage() + "</h1>");
}
}
}
}
}

******* "MostrarProductosServlet" ****


*************************************

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet(name = "MostrarProductosServlet", urlPatterns = {"/mostrar_productos"})


public class MostrarProductosServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
// Establecer la conexión a la base de datos
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/productos_db?
serverTimezone=UTC", "root", "123456");

// Consultar los productos


String sql = "SELECT Id,nombre, descripcion, precio, stock FROM
productos";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();

// Construir la tabla de productos en HTML


StringBuilder tablaHTML = new StringBuilder();
while (rs.next()) {
tablaHTML.append("<tr>");

tablaHTML.append("<td>").append(rs.getInt("Id")).append("</td>");

tablaHTML.append("<td>").append(rs.getString("nombre")).append("</td>");

tablaHTML.append("<td>").append(rs.getString("descripcion")).append("</td>");

tablaHTML.append("<td>").append(rs.getDouble("precio")).append("</td>");

tablaHTML.append("<td>").append(rs.getInt("stock")).append("</td>");
tablaHTML.append("</tr>");
}

// Enviar la tabla HTML como respuesta


out.println(tablaHTML.toString());
} catch (ClassNotFoundException | SQLException ex) {
out.println("<h1>Error de base de datos: " + ex.getMessage() +
"</h1>");
} finally {
// Cerrar la conexión y liberar recursos
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
out.println("<h1>Error al cerrar la conexión: " +
ex.getMessage() + "</h1>");
}
}
}
}
}

También podría gustarte