0% found this document useful (0 votes)
30 views11 pages

Codigo HTML, Server

Uploaded by

jessperez272
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views11 pages

Codigo HTML, Server

Uploaded by

jessperez272
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

<%--

Document : ELIMINAR
Created on : 15 may 2024, 09:44:32
Author : JESSI PEREZ
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Eliminar Producto</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container mt-5" class="mx-auto" style="width: 600px;">
<h2 class="mb-4">Ingrese id empleado a eliminar</h2>
<form id="eliminarProductoForm" action="EliminarServlet" method="post">
<div class="form-group">
<label for="id">ID Empleado</label>
<input type="number" class="form-control" id="id" name="id"
required>
</div>
<button type="submit" class="btn btn-danger">Eliminar empleado</button>
</form>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></
script>
</body>
</html>

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit
this template
*/

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 = "EliminarServlet", urlPatterns = {"/eliminar_producto"})
public class EliminarServlet 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/prueba_bd?
serverTimezone=UTC", "root", "123456");

// Crear la consulta SQL para eliminar el producto


String sql = "DELETE FROM Empleados 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>");
}
}
}
}
}

GUARDAR

<%--
Document : INGRESAR
Created on : 15 may 2024, 08:50:10
Author : JESSI PEREZ
--%>

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>INSERTAR REGISTROS</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
<style>
/* Estilos adicionales para el formulario */
.formulario {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="formulario">
<h2 class="mb-4">Registros Empleados</h2>
<form id="formularioProducto" action="GuardarEmpleadosServlet"
method="post">
<div class="form-group">
<label for="nombre">Nombre empleado</label>
<input type="text" class="form-control" id="nombre"
name="nombre" required>
</div>
<div class="form-group">
<label for="apellidos">Apellido empleado</label>
<input type="text" class="form-control" id="apellidos"
name="apellidos" required>
</div>
<div class="form-group">
<label for="correo">Correo electronico:</label>
<input type="email" class="form-control" id="correo"
name="correo" required>
</div>
<div class="form-group">
<label for="direccion">Direccion:</label>
<input type="text" class="form-control" id="direccion"
name="direccion" required>
</div>
<button type="submit" class="btn btn-primary">Guardar
Producto</button>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></
script>
</body>
</html>

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit
this template
*/

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;

@WebServlet(name = "GuardarEmpleadosServlet", urlPatterns =


{"/GuardarEmpleadosServlet"})
public class GuardarEmpleadosServlet 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 apellidos = request.getParameter("apellidos");
String correo = request.getParameter("correo");
String direccion = request.getParameter("direccion");

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


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

// Crear la consulta SQL para insertar el producto


String sql = "INSERT INTO Empleados (nombre, apellido, correo,
direccion) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, nombre);
stmt.setString(2, apellidos);
stmt.setString(3, correo);
stmt.setString(4, direccion);

// 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>");
}
}
}
}
}

<%--
Document : MODIFICAR
Created on : 15 may 2024, 10:18:51
Author : JESSI PEREZ
--%>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modificar Registro</title>
<!-- Bootstrap CSS -->
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h2>Ingrese id del empleado que desea modificar</h2>
<form id="modifyForm" action="ModifyServlet" method="post">
<div class="form-group">
<label for="id">ID:</label>
<input type="text" class="form-control" id="id" name="id">
</div>
<div class="form-group">
<label for="nombre">Nuevo nombre:</label>
<input type="text" class="form-control" id="nombre" name="nombre">
</div>
<div class="form-group">
<label for="apellidos">Nuevo apellido:</label>
<input type="text" class="form-control" id="apellidos"
name="apellidos">
</div>
<div class="form-group">
<label for="correo">Nuevo correo electronico:</label>
<input type="email" class="form-control" id="correo" name="correo">
</div>
<div class="form-group">
<label for="direccion">Nueva direccion:</label>
<input type="text" class="form-control" id="direccion"
name="direccion">
</div>
<button type="submit" class="btn btn-primary">Modificar</button>
</form>
</div>
<!-- jQuery -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Custom JavaScript -->
<script>

$(document).ready(function() {
$('#modifyForm').submit(function(event) {
event.preventDefault();
var id = $('#id').val();
var nombre = $('#nombre').val();
var apellidos = $('#apellidos').val();
var correo = $('#correo').val();
var direccion = $('#direccion').val();
$.ajax({
type: 'POST',
url: 'ModifyServlet',
data: {
id: id,
nombre: nombre,
apellidos: apellidos,
correo: correo,
direccion: direccion
},
success: function(response) {
alert('Registro modificado exitosamente.');
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
alert('Error al modificar el registro. Por favor, inténtalo de
nuevo.');
}
});
});
});
</script>
</body>
</html>

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit
this template
*/

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.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

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


public class ModifyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// Recuperar los parámetros del formulario


String id = request.getParameter("id");
String nombre = request.getParameter("nombre");
String apellido = request.getParameter("apellido");
String correo = request.getParameter("correo");
String direccion = request.getParameter("direccion");

System.out.println("id: " + id);


System.out.println("nombre: " + nombre);
System.out.println("apellido: " + apellido);
System.out.println("correo: " + correo);
System.out.println("direccion: " + direccion);

// Variables de conexión y declaración


Connection con = null;
PreparedStatement stmt = null;

try {
// Establecer la conexión a la base de datos
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/prueba_bd?
serverTimezone=UTC", "root", "123456");

// Preparar la consulta SQL para actualizar el registro


String sql = "UPDATE Empleados SET nombre = ?, apellido = ?, correo
= ?, direccion = ? WHERE id = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, nombre);
stmt.setString(2, apellido);
stmt.setString(3, correo);
stmt.setString(4, direccion);
stmt.setString(5, id);

// Ejecutar la consulta
int rowsAffected = stmt.executeUpdate();

if (rowsAffected > 0) {
// Si se modificó correctamente, enviar una respuesta exitosa al
cliente
out.println("Registro modificado exitosamente.");
response.setStatus(HttpServletResponse.SC_OK);
} else {
// Si no se modificó ningún registro, enviar un mensaje de error
out.println("No se encontró ningún registro con el ID
proporcionado.");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
} catch (ClassNotFoundException | SQLException ex) {
// Manejar cualquier excepción que pueda ocurrir durante el proceso
out.println("Error al modificar el registro: " + ex.getMessage());
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
}
out.close();
}
}
}

<%--
Document : MOSTRAR
Created on : 15 may 2024, 09:48:50
Author : JESSI PEREZ
--%>

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mostrar Empleados</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
<style>
.formulario {
max-width: 400px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="container" class="mx-auto" style="width: 1000px;" class="table-
responsive">
<div class="formulario">
<h1>Ingrese id empleado que desea mostrar</h1>
<form method="GET" action="MostrarEmpleadosServlet" onsubmit="return
validarFormulario();">
<div class="row mt-3">
<div class="col-md-4">
<div class="mb-3">
<label for="employeeId" class="form-label">ID de
Empleado</label>
<input type="text" class="form-control" id="employeeId"
name="id">
</div>
<button type="submit" class="btn btn-primary mb-3">Mostrar
Datos</button>
<button type="button" class="btn btn-warning mb-3"
onclick="modificarDatos()">Modificar</button>
</div>
</div>
</form>
<div id="resultado" class="mt-4"></div>
</div>
</div>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/
bootstrap.bundle.min.js"></script>
<script>
function validarFormulario() {
var id = document.getElementById("employeeId").value;

if (id.trim() === "") {


alert("Por favor ingresa un ID de empleado válido.");
return false; // Evita que el formulario se envíe si el campo está
vacío
}
return true; // Permite que el formulario se envíe si la validación es
exitosa
}

function modificarDatos() {
var id = document.getElementById("employeeId").value;

if (id.trim() === "") {


alert("Por favor ingresa un ID de empleado válido.");
return;
}

window.location.href = 'modificar.jsp?id=' + id;


}
</script>
</body>
</html>

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit
this template
*/

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 = "MostrarEmpleadosServlet", urlPatterns =


{"/MostrarEmpleadosServlet"})
public class MostrarEmpleadosServlet 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()) {
String id = request.getParameter("id");

Connection conn = null;


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

String sql = "SELECT id, nombre, apellido, correo, direccion FROM


Empleados WHERE id = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, Integer.parseInt(id));
rs = stmt.executeQuery();

if (rs.next()) {
out.println("<table class='table
table-bordered'><tr><th>ID</th><th>Nombre</th><th>Apellido</th><th>Correo</
th><th>Dirección</th></tr>");
out.println("<tr>");
out.println("<td>" + rs.getInt("id") + "</td>");
out.println("<td>" + rs.getString("nombre") + "</td>");
out.println("<td>" + rs.getString("apellido") + "</td>");
out.println("<td>" + rs.getString("correo") + "</td>");
out.println("<td>" + rs.getString("direccion") + "</td>");
out.println("</tr>");
out.println("</table>");
} else {
out.println("<h1>No se encontró ningún registro con el ID
proporcionado.</h1>");
}
} catch (ClassNotFoundException | SQLException ex) {
out.println("<h1>Error de base de datos: " + ex.getMessage() +
"</h1>");
} finally {
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>");
}
}
}
}
}

You might also like