Sistema de Gestión de Usuarios con Java Web

Classified in Computers

Written on in English with a size of 21.85 KB

Archivos HTML del Frontend

INDEX.HTML: Menú Principal del Sistema

<!DOCTYPE html>
<html>
<head>
    <title>Menú Principal del Sistema</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        h2 { color: #789; font-size: 45px; }
        select { color: brown; font-size: 30px; }
        h3 { color: #8b4513; font-size: 30px; }
    </style>
</head>
<body>
    <h2>Menú de Opciones del Sistema</h2>
    <h3>Seleccione una opción:</h3>
    <ol>
        <li><a href="Registro.html">Registrar Usuario</a></li>
        <li><a href="Acceso.html">Acceso al Sistema</a></li>
    </ol>
</body>
</html>

REGISTRO.HTML: Formulario de Registro de Usuario

<!DOCTYPE html>
<html>
<head>
    <title>Registro de Nuevo Usuario</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        h2 { color: #d87093; font-size: 40px; }
        select { color: brown; font-size: 30px; }
        h3 { color: purple; font-size: 30px; }
        input[type="submit"] {
            background-color: #e9967a;
            color: #000;
            font-size: 20px;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h2>Registro de Usuario</h2>
    <h3>Complete el formulario para registrarse:</h3>
    <form action="Registro.jsp" method="post">
        <p>Nombre: <input type="text" name="nombre"></p>
        <p>Correo: <input type="email" name="correo"></p>
        <p><input type="submit" value="Registrar"></p>
    </form>
</body>
</html>

ACCESO.HTML: Formulario de Acceso al Sistema

<!DOCTYPE html>
<html>
<head>
    <title>Acceso Seguro al Sistema</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        h2 { color: #87cefa; font-size: 40px; }
        select { color: brown; font-size: 30px; }
        h3 { color: #ff4500; font-size: 30px; }
        input[type="submit"] {
            background-color: hotpink;
            color: #000;
            font-size: 20px;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h2>Acceso al Sistema</h2>
    <h3>Ingrese sus credenciales:</h3>
    <form action="Acceso.jsp" method="post">
        <p>Usuario: <input type="text" name="user"></p>
        <p>Contraseña: <input type="password" name="pass"></p>
        <p><input type="submit" value="Validar"></p>
    </form>
</body>
</html>

Archivos JSP (Backend)

Los siguientes archivos JSP son mencionados en el frontend, pero su contenido no fue proporcionado en el documento original:

  • REGISTRO.JSP
  • ACCESO.JSP

Clases Java del Backend

CONEXION.JAVA: Conexión a Base de Datos

package beans;

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;

/**

Clase de utilidad para establecer conexión con la base de datos SQL Server. @author Estela */ public class Conexion { /** Establece y retorna una conexión a la base de datos. @return Objeto Connection si la conexión es exitosa, null en caso de error. */ public static Connection conectar() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection cn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Encuesta;user=sa;password=sasa;"); return cn; } catch (ClassNotFoundException e) { System.err.println("Error: Driver JDBC de SQL Server no encontrado. " + e.getMessage()); return null; } catch (SQLException e) { System.err.println("Error de conexión a la base de datos: " + e.getMessage()); return null; } catch (Exception e) { System.err.println("Error inesperado al conectar a la base de datos: " + e.getMessage()); return null; } } }

ENCRIPTARMD5.JAVA: Utilidad de Encriptación MD5

package beans;

import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;

/**

Clase de utilidad para encriptar cadenas de texto usando el algoritmo MD5. */ public class EncriptarMD5 { private static final char[] CONSTS_HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

/**

Encripta una cadena de texto utilizando el algoritmo MD5. @param stringToEncrypt La cadena de texto a encriptar. @return La cadena encriptada en formato hexadecimal, o null si el algoritmo MD5 no está disponible. / public static String encripta(String stringToEncrypt) { try { MessageDigest msgd = MessageDigest.getInstance("MD5"); byte[] bytes = msgd.digest(stringToEncrypt.getBytes()); StringBuilder strbCadenaMD5 = new StringBuilder(2 bytes.length); for (int i = 0; i < bytes.length; i++) { int low = (int) (bytes[i] & 0x0f); int high = (int) ((bytes[i] & 0xf0) >> 4); strbCadenaMD5.append(CONSTS_HEX[high]); strbCadenaMD5.append(CONSTS_HEX[low]); } return strbCadenaMD5.toString(); } catch (NoSuchAlgorithmException e) { System.err.println("Error: Algoritmo MD5 no disponible. " + e.getMessage()); return null; } } }

JMAIL.java: Servicio de Envío de Correos

package beans;

import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.swing.JOptionPane;

/**

Clase de utilidad para el envío de correos electrónicos utilizando SMTP de Yahoo.

Soporta envío de mensajes simples, a múltiples destinatarios y con archivos adjuntos.

@author Estela Martínez Cruz */ public class JMail {

// Credenciales de la cuenta de correo Yahoo public static String Username = "correoyahoo"; // Consider using environment variables or configuration files for sensitive data public static String PassWord = "password"; // Consider using environment variables or configuration files for sensitive data

/**

Envía un correo electrónico a un único destinatario.

@param to Dirección de correo del destinatario.

@param message Contenido del mensaje.

@param subject Asunto del correo. */ public static void sendMail(String to, String message, String subject) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.mail.yahoo.com"); props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Username, PassWord); } });

try { Message mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(Username)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject(subject); mimeMessage.setText(message);

 Transport.send(mimeMessage);
 JOptionPane.showMessageDialog(null, "Su mensaje ha sido enviado exitosamente.");

} catch (MessagingException e) { System.err.println("Error al enviar el mensaje: " + e.getMessage()); throw new RuntimeException("Error al enviar el mensaje: " + e.getMessage(), e); } }

/**

Envía un correo electrónico a múltiples destinatarios.

@param recipients Array de direcciones de correo de los destinatarios.

@param message Contenido del mensaje.

@param subject Asunto del correo. */ public static void sendMail(InternetAddress[] recipients, String message, String subject) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.mail.yahoo.com"); props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Username, PassWord); } });

try { Message mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(Username)); mimeMessage.setSubject(subject); mimeMessage.setText(message); mimeMessage.addRecipients(Message.RecipientType.TO, recipients);

 Transport.send(mimeMessage);
 JOptionPane.showMessageDialog(null, "Sus mensajes se han enviado exitosamente.");

} catch (MessagingException e) { System.err.println("Error al enviar mensajes a múltiples destinatarios: " + e.getMessage()); throw new RuntimeException("Error al enviar mensajes a múltiples destinatarios: " + e.getMessage(), e); } }

/**

Envía un correo electrónico a un único destinatario con un archivo adjunto.

@param to Dirección de correo del destinatario.

@param message Contenido del mensaje.

@param subject Asunto del correo.

@param filePath Ruta del archivo a adjuntar. */ public static void sendMail(String to, String message, String subject, String filePath) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.mail.yahoo.com"); props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Username, PassWord); } }); try { BodyPart textPart = new MimeBodyPart(); textPart.setText(message);

 BodyPart attachmentPart = new MimeBodyPart();
 FileDataSource fileDataSource = new FileDataSource(filePath);
 attachmentPart.setDataHandler(new DataHandler(fileDataSource));
 attachmentPart.setFileName(fileDataSource.getName());

 MimeMultipart multipart = new MimeMultipart();
 multipart.addBodyPart(textPart);
 multipart.addBodyPart(attachmentPart);

 Message mimeMessage = new MimeMessage(session);
 mimeMessage.setFrom(new InternetAddress(Username));
 mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
 mimeMessage.setSubject(subject);
 mimeMessage.setContent(multipart);

 Transport.send(mimeMessage);
 JOptionPane.showMessageDialog(null, "Su archivo se ha enviado exitosamente.");

} catch (MessagingException e) { System.err.println("Error al enviar el archivo: " + e.getMessage()); throw new RuntimeException("Error al enviar el archivo: " + e.getMessage(), e); } }

/**

Envía un correo electrónico a múltiples destinatarios con un archivo adjunto.

@param recipients Array de direcciones de correo de los destinatarios.

@param message Contenido del mensaje.

@param subject Asunto del correo.

@param filePath Ruta del archivo a adjuntar. */ public static void sendMail(InternetAddress[] recipients, String message, String subject, String filePath) { try { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.mail.yahoo.com"); props.put("mail.smtp.port", "587");

 Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
             @Override
             protected PasswordAuthentication getPasswordAuthentication() {
                 return new PasswordAuthentication(Username, PassWord);
             }
         });

 BodyPart textPart = new MimeBodyPart();
 textPart.setText(message);

 BodyPart attachmentPart = new MimeBodyPart();
 FileDataSource fileDataSource = new FileDataSource(filePath);
 attachmentPart.setDataHandler(new DataHandler(fileDataSource));
 attachmentPart.setFileName(fileDataSource.getName());

 MimeMultipart multipart = new MimeMultipart();
 multipart.addBodyPart(textPart);
 multipart.addBodyPart(attachmentPart);

 Message mimeMessage = new MimeMessage(session);
 mimeMessage.setFrom(new InternetAddress(Username));
 mimeMessage.setSubject(subject);
 mimeMessage.addRecipients(Message.RecipientType.TO, recipients);
 mimeMessage.setContent(multipart);

 Transport.send(mimeMessage);
 JOptionPane.showMessageDialog(null, "Su archivo se ha enviado exitosamente.");

} catch (MessagingException e) { System.err.println("Error en el envío de archivo a múltiples destinatarios: " + e.getMessage()); throw new RuntimeException("Error en el envío de archivo a múltiples destinatarios: " + e.getMessage(), e); } } }

USUARIOS.java: Lógica de Negocio de Usuarios

package beans;

import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;

/**

Clase para la gestión de usuarios, incluyendo registro, autenticación y generación de contraseñas. */ public class Usuarios { private String nombre; private String correo; private String password; private String tipo; private String respuesta; // Used for messages back to the user/JSP private int idUsuario; private int opcion; // Used to trigger actions based on user input

// Getters and Setters public String getNombre() { return nombre; }

public void setNombre(String nombre) { this.nombre = nombre; }

public String getCorreo() { return correo; }

public void setCorreo(String correo) { this.correo = correo; }

public String getPassword() { return password; }

public void setPassword(String password) { this.password = password; }

public String getTipo() { return tipo; }

public void setTipo(String tipo) { this.tipo = tipo; }

public String getRespuesta() { return respuesta; }

public void setRespuesta(String respuesta) { this.respuesta = respuesta; }

public int getIdUsuario() { return idUsuario; }

public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; }

public int getOpcion() { return opcion; }

/**

Establece la opción de operación (guardar o buscar) y la ejecuta. @param opcion 1 para guardar, 2 para buscar. */ public void setOpcion(int opcion) { this.opcion = opcion; switch (opcion) { case 1: guardar(); break; case 2: buscar(); break; default: this.respuesta = "Opción no válida."; break; } }

/**

Guarda un nuevo usuario en la base de datos.

Genera una contraseña temporal y la encripta antes de almacenarla. */ public void guardar() { String generatedPassword = generaPassword(); // Store the generated password String encryptedPassword = EncriptarMD5.encripta(generatedPassword);

if (encryptedPassword == null) { respuesta = "Error al encriptar la contraseña."; return; }

try (Connection c = Conexion.conectar()) { if (c != null) { PreparedStatement ps = c.prepareStatement("INSERT INTO usuarios(nombre, correo, password, tipo) VALUES (?, ?, ?, ?)"); ps.setString(1, nombre); ps.setString(2, correo); ps.setString(3, encryptedPassword); ps.setString(4, "E"); // Default type 'E' for Empleado ps.execute(); respuesta = "Dato almacenado exitosamente. Tu contraseña es: " + generatedPassword; } else { respuesta = "No se pudo establecer conexión con la base de datos."; } } catch (SQLException e) { respuesta = "Error al guardar el usuario: " + e.getMessage(); System.err.println("Error SQL al guardar usuario: " + e.getMessage()); } catch (Exception e) { respuesta = "Error inesperado al guardar el usuario: " + e.getMessage(); System.err.println("Error inesperado al guardar usuario: " + e.getMessage()); } }

/**

Busca un usuario en la base de datos por nombre y contraseña.

Establece el tipo de usuario en la respuesta si las credenciales son válidas. */ public void buscar() { try (Connection c = Conexion.conectar()) { if (c != null) { String encryptedPassword = EncriptarMD5.encripta(password); if (encryptedPassword == null) { respuesta = "Error al encriptar la contraseña para la búsqueda."; return; }

     PreparedStatement ps = c.prepareStatement("SELECT tipo FROM usuarios WHERE nombre = ? AND password = ?");
     ps.setString(1, nombre);
     ps.setString(2, encryptedPassword);
     ResultSet rs = ps.executeQuery();

     if (rs.next()) {
         String userType = rs.getString(1);
         switch (userType.charAt(0)) {
             case 'S':
                 respuesta = "Eres una Secretaria.&lt;br&gt;&lt;a href='index.html'&gt;Volver al Inicio&lt;/a&gt;";
                 break;
             case 'A':
                 respuesta = "Eres un Administrador.&lt;br&gt;&lt;a href='index.html'&gt;Volver al Inicio&lt;/a&gt;";
                 break;
             case 'E':
                 respuesta = "Eres un Empleado.&lt;br&gt;&lt;a href='index.html'&gt;Volver al Inicio&lt;/a&gt;";
                 break;
             case 'I':
                 respuesta = "Eres un Invitado.&lt;br&gt;&lt;a href='index.html'&gt;Volver al Inicio&lt;/a&gt;";
                 break;
             default:
                 respuesta = "Tipo de usuario desconocido.";
                 break;
         }
     } else {
         respuesta = "Verifica tus datos. Usuario o contraseña incorrectos.";
     }
 } else {
     respuesta = "No hay conexión a la base de datos.";
 }

} catch (SQLException e) { respuesta = "Error al buscar el usuario: " + e.getMessage(); System.err.println("Error SQL al buscar usuario: " + e.getMessage()); } catch (Exception e) { respuesta = "Error inesperado al buscar el usuario: " + e.getMessage(); System.err.println("Error inesperado al buscar usuario: " + e.getMessage()); } }

/**

Genera una contraseña temporal basada en el nombre del usuario.

La contraseña se forma con las primeras 3 letras del primer apellido y las primeras 3 letras del segundo apellido (si existen),

seguido de un número aleatorio de 3 dígitos.

@return La contraseña generada. */ public String generaPassword() { String[] nameParts = nombre.split(" "); StringBuilder generatedPass = new StringBuilder();

if (nameParts.length >= 1) { generatedPass.append(nameParts[0].substring(0, Math.min(nameParts[0].length(), 3))); }

if (nameParts.length == 3) { if (nameParts[1].length() > 0) { generatedPass.append(nameParts[1].substring(0, Math.min(nameParts[1].length(), 3))); } } else if (nameParts.length == 4) { if (nameParts[2].length() > 0) { generatedPass.append(nameParts[2].substring(0, Math.min(nameParts[2].length(), 3))); } }

generatedPass.append(generaNumero()); String finalPassword = generatedPass.toString(); this.respuesta = finalPassword; return finalPassword; }

/**

Genera un número aleatorio de 3 dígitos (000-999). @return El número aleatorio formateado como cadena de 3 dígitos. / public String generaNumero() { int w = (int) (Math.random() 1000); if (w < 10) { return "00" + w; } else if (w < 100) { return "0" + w; } else { return "" + w; } } }

Related entries: