Ejemplos de Formularios JSP con Java y MySQL: Registro de Usuarios, Productos, Estudiantes y Citas
Ejemplos de Formularios JSP con Java y MySQL
En este documento se presentan cuatro ejemplos completos de aplicaciones web desarrolladas con JSP, Servlets y MySQL, siguiendo el patrón Modelo-Vista-Controlador (MVC). Cada ejemplo incluye un formulario, una clase modelo, un controlador y una vista de confirmación.
1. Registro de Usuario
formulario.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Formulario de Usuario</title>
</head>
<body>
<h2>Registro de Usuario</h2>
<form action="registrar" method="post">
Nombre: <input type="text" name="nombre" required>
Género:
<input type="radio" name="genero" value="Masculino" checked> Masculino
<input type="radio" name="genero" value="Femenino"> Femenino
<input type="radio" name="genero" value="Otro"> Otro
Correo: <input type="email" name="correo" required>
País:
<select name="pais">
<option value="México">México</option>
<option value="Colombia">Colombia</option>
<option value="España">España</option>
</select>
</form>
</body>
</html>
vista.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ page import="modelo.Usuario" %>
<!DOCTYPE html>
<html>
<head>
<title>Datos del Usuario</title>
</head>
<body>
<h2>Información Recibida</h2>
<p><strong>Nombre:</strong> <%= u.getNombre() %></p>
<p><strong>Género:</strong> <%= u.getGenero() %></p>
<p><strong>Correo:</strong> <%= u.getCorreo() %></p>
<p><strong>País:</strong> <%= u.getPais() %></p>
</body>
</html>
Usuario.java
package modelo;
public class Usuario {
private String nombre;
private String genero;
private String correo;
private String pais;
public Usuario() {}
public Usuario(String nombre, String genero, String correo, String pais) {
this.nombre = nombre;
this.genero = genero;
this.correo = correo;
this.pais = pais;
}
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getGenero() { return genero; }
public void setGenero(String genero) { this.genero = genero; }
public String getCorreo() { return correo; }
public void setCorreo(String correo) { this.correo = correo; }
public String getPais() { return pais; }
public void setPais(String pais) { this.pais = pais; }
}
RegistroUsuario.java
package controlador;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import modelo.Usuario;
import java.sql.*;
public class RegistroUsuario extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nombre = request.getParameter("nombre");
String genero = request.getParameter("genero");
String correo = request.getParameter("correo");
String pais = request.getParameter("pais");
Usuario usuario = new Usuario(nombre, genero, correo, pais);
request.setAttribute("usuario", usuario);
// Conexión e inserción
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tu_basedatos", "usuario", "clave");
String sql = "INSERT INTO usuario (nombre, genero, correo, pais) VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, nombre);
ps.setString(2, genero);
ps.setString(3, correo);
ps.setString(4, pais);
ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("vista.jsp").forward(request, response);
}
}
2. Registro de Producto
formulario.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Formulario de Producto</title>
</head>
<body>
<h2>Registro de Producto</h2>
<form action="registrar" method="post">
Nombre: <input type="text" name="nombre" required>
Categoría:
<select name="categoria">
<option value="Electrónica">Electrónica</option>
<option value="Ropa">Ropa</option>
<option value="Hogar">Hogar</option>
</select>
Precio: <input type="number" step="0.01" name="precio" required>
Descripción:
<textarea name="descripcion" rows="4" cols="50"></textarea>
</form>
</body>
</html>
Detalle.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ page import="modelo.Producto" %>
<!DOCTYPE html>
<html>
<head>
<title>Producto Registrado</title>
</head>
<body>
<h2>Datos del Producto</h2>
<p><strong>Nombre:</strong> <%= p.getNombre() %></p>
<p><strong>Categoría:</strong> <%= p.getCategoria() %></p>
<p><strong>Precio:</strong> $<%= p.getPrecio() %></p>
<p><strong>Descripción:</strong> <%= p.getDescripcion() %></p>
</body>
</html>
Producto.java
package modelo;
public class Producto {
private String nombre;
private String categoria;
private double precio;
private String descripcion;
public Producto() {}
public Producto(String nombre, String categoria, double precio, String descripcion) {
this.nombre = nombre;
this.categoria = categoria;
this.precio = precio;
this.descripcion = descripcion;
}
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getCategoria() { return categoria; }
public void setCategoria(String categoria) { this.categoria = categoria; }
public double getPrecio() { return precio; }
public void setPrecio(double precio) { this.precio = precio; }
public String getDescripcion() { return descripcion; }
public void setDescripcion(String descripcion) { this.descripcion = descripcion; }
}
RegistroProducto.java
package controlador;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import modelo.Producto;
import java.sql.*;
public class RegistroProducto extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nombre = request.getParameter("nombre");
String categoria = request.getParameter("categoria");
double precio = Double.parseDouble(request.getParameter("precio"));
String descripcion = request.getParameter("descripcion");
Producto producto = new Producto(nombre, categoria, precio, descripcion);
request.setAttribute("producto", producto);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tu_basedatos", "usuario", "clave");
String sql = "INSERT INTO producto (nombre, categoria, precio, descripcion) VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, nombre);
ps.setString(2, categoria);
ps.setDouble(3, precio);
ps.setString(4, descripcion);
ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("detalle.jsp").forward(request, response);
}
}
3. Registro de Estudiante
formulario.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Formulario de Estudiante</title>
</head>
<body>
<h2>Registro de Estudiante</h2>
<form action="registrar" method="post">
Nombre: <input type="text" name="nombre" required>
Matrícula: <input type="text" name="matricula" required>
Carrera:
<select name="carrera">
<option value="Ingeniería">Ingeniería</option>
<option value="Administración">Administración</option>
<option value="Contaduría">Contaduría</option>
</select>
Semestre: <input type="number" name="semestre" min="1" max="12" required>
</form>
</body>
</html>
datos.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ page import="modelo.Estudiante" %>
<!DOCTYPE html>
<html>
<head>
<title>Estudiante Registrado</title>
</head>
<body>
<h2>Datos del Estudiante</h2>
<p><strong>Nombre:</strong> <%= e.getNombre() %></p>
<p><strong>Matrícula:</strong> <%= e.getMatricula() %></p>
<p><strong>Carrera:</strong> <%= e.getCarrera() %></p>
<p><strong>Semestre:</strong> <%= e.getSemestre() %></p>
</body>
</html>
Estudiante.java
package modelo;
public class Estudiante {
private String nombre;
private String matricula;
private String carrera;
private int semestre;
public Estudiante() {}
public Estudiante(String nombre, String matricula, String carrera, int semestre) {
this.nombre = nombre;
this.matricula = matricula;
this.carrera = carrera;
this.semestre = semestre;
}
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getMatricula() { return matricula; }
public void setMatricula(String matricula) { this.matricula = matricula; }
public String getCarrera() { return carrera; }
public void setCarrera(String carrera) { this.carrera = carrera; }
public int getSemestre() { return semestre; }
public void setSemestre(int semestre) { this.semestre = semestre; }
}
RegistroEstudiante.java
package controlador;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import modelo.Estudiante;
import java.sql.*;
public class RegistroEstudiante extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nombre = request.getParameter("nombre");
String matricula = request.getParameter("matricula");
String carrera = request.getParameter("carrera");
int semestre = Integer.parseInt(request.getParameter("semestre"));
Estudiante estudiante = new Estudiante(nombre, matricula, carrera, semestre);
request.setAttribute("estudiante", estudiante);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tu_basedatos", "usuario", "clave");
String sql = "INSERT INTO estudiante (nombre, matricula, carrera, semestre) VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, nombre);
ps.setString(2, matricula);
ps.setString(3, carrera);
ps.setInt(4, semestre);
ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("datos.jsp").forward(request, response);
}
}
4. Agendar Cita Médica
formulario.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Agendar Cita Médica</title>
</head>
<body>
<h2>Formulario de Cita Médica</h2>
<form action="registrar" method="post">
Paciente: <input type="text" name="paciente" required>
Especialidad:
<select name="especialidad">
<option value="Cardiología">Cardiología</option>
<option value="Pediatría">Pediatría</option>
<option value="Odontología">Odontología</option>
<option value="Dermatología">Dermatología</option>
</select>
Fecha: <input type="date" name="fecha" required>
Hora: <input type="time" name="hora" required>
</form>
</body>
</html>
confirmacion.jsp
<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ page import="modelo.CitaMedica" %>
<!DOCTYPE html>
<html>
<head>
<title>Confirmación de Cita</title>
</head>
<body>
<h2>Cita Médica Agendada</h2>
<p><strong>Paciente:</strong> <%= c.getPaciente() %></p>
<p><strong>Especialidad:</strong> <%= c.getEspecialidad() %></p>
<p><strong>Fecha:</strong> <%= c.getFecha() %></p>
<p><strong>Hora:</strong> <%= c.getHora() %></p>
</body>
</html>
CitaMedica.java
package modelo;
public class CitaMedica {
private String paciente;
private String especialidad;
private String fecha;
private String hora;
public CitaMedica() {}
public CitaMedica(String paciente, String especialidad, String fecha, String hora) {
this.paciente = paciente;
this.especialidad = especialidad;
this.fecha = fecha;
this.hora = hora;
}
public String getPaciente() { return paciente; }
public void setPaciente(String paciente) { this.paciente = paciente; }
public String getEspecialidad() { return especialidad; }
public void setEspecialidad(String especialidad) { this.especialidad = especialidad; }
public String getFecha() { return fecha; }
public void setFecha(String fecha) { this.fecha = fecha; }
public String getHora() { return hora; }
public void setHora(String hora) { this.hora = hora; }
}
RegistroCita.java
package controlador;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import modelo.CitaMedica;
import java.sql.*;
public class RegistroCita extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String paciente = request.getParameter("paciente");
String especialidad = request.getParameter("especialidad");
String fecha = request.getParameter("fecha");
String hora = request.getParameter("hora");
CitaMedica cita = new CitaMedica(paciente, especialidad, fecha, hora);
request.setAttribute("cita", cita);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tu_basedatos", "usuario", "clave");
String sql = "INSERT INTO cita_medica (paciente, especialidad, fecha, hora) VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, paciente);
ps.setString(2, especialidad);
ps.setString(3, fecha);
ps.setString(4, hora);
ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("confirmacion.jsp").forward(request, response);
}
}
Scripts SQL de las tablas
Tabla usuario
CREATE TABLE usuario (
id INT AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(100),
genero VARCHAR(20),
correo VARCHAR(100),
pais VARCHAR(50)
);
Tabla producto
CREATE TABLE producto (
id INT AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(100),
categoria VARCHAR(50),
precio DECIMAL(10,2),
descripcion TEXT
);
Tabla estudiante
CREATE TABLE estudiante (
id INT AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(100),
matricula VARCHAR(20),
carrera VARCHAR(50),
semestre INT
);
Tabla cita_medica
CREATE TABLE cita_medica (
id INT AUTO_INCREMENT PRIMARY KEY,
paciente VARCHAR(100),
especialidad VARCHAR(50),
fecha DATE,
hora TIME
);