Este post será un complemento adicional a los temas ya vistos en el curso de Lenguaje de Programación II en donde aprendimos a crear una aplicación web Java en Eclipse con Servlets y JSPs. En esta oportunidad añadiremos a los temas de este curso el uso de Maven, que es una herramienta de software para la gestión y construcción de proyectos.
Vamos a crear un pequeño CRUD a una tabla Productos siguiendo los mismos pasos que hemos venido usando en el curso. Anteriormente, ya hemos creado mantenimientos en Java usando MVC, DAO y DTO. Asimismo, hemos visto lo que son los properties, internacionalización, etiquetas personalizadas, AJAX, entre otros tópicos. En este post, partiremos por crear un nuevo proyecto web dinámico (Dynamic Web Project) y lo convertiremos a un Proyecto Maven (Maven Project). Después de ello, crearemos las dependencias y construiremos la estructura de nuestro proyecto que realizará un CRUD a una tabla Productos usando el patrón DAO.
La diferencia del proyecto que construiremos ahora es que con el uso de Maven ya no tendremos que estar agregando las librerías que usará nuestro proyecto de manera manual, sino que haremos uso del repositorio de Maven para descargar la librerías de manera automática.
¿Qué es Maven?
Normalmente cuando trabajamos con Java/JavaEE el uso de librerías es algo común como en cualquier otro lenguaje de programación. Sin embargo, una librería puede depender de otras librerías para funcionar de forma correcta. Por ende, su gestión se puede volver tedioso a la hora de buscar las librerías y ver que versión exacta debemos de elegir. Así pues necesitamos más información para gestionarlo todo de forma correcta y para ellos existe MAVEN, que es una herramienta que nos va a permitir tener una gestión correcta de nuestra librerías, proyectos y dependencias. Dentro de un proyecto Maven el archivo pom.xml (Proyect Object Model) es el de mayor importancia ya que contiene toda la información del artefacto que usará nuestro proyecto. Un Artefacto puede verse como una librería con esteroides (aunque agrupa mas conceptos). Contiene las clases propias de la librería pero ademas incluye toda la información necesaria para su correcta gestión (grupo, versión, dependencias etc).
1. Crea un Dynamic Web Project
1) Clic en File>New>Dynamic Web Project
Si no aparece la opción Dynamic Web Project hacemos clic en:
File>New>Other>Web>Dynamic Web Project
2) Escribimos el nombre de nuestro proyecto, seleccionamos el servidor de Apache Tomcat y damos clic en Finish.
- Para configurar el servidor de Apache Tomcat, debemos hacer clic en New Runtine y ubicar la carpeta en donde lo tenemos instalado.
Tendremos la siguiente estructura
1. Convertir un Dynamic Web Project a Maven Project
1) Clic derecho al proyecto Configure/Convert to Maven Project
2) En la siguiente ventana dejamos por defecto y damos clic en Finish
Tendremos la siguiente estructura
Como podemos observar nos creo el siguiente archivo pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | < project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelversion >4.0.0</ modelVersion > < groupid >Crud-Java</ groupId > < artifactid >Crud-Java</ artifactId > < version >0.0.1-SNAPSHOT</ version > < packaging >war</ packaging > < build > < sourcedirectory >src</ sourceDirectory > < plugins > < plugin > < artifactid >maven-compiler-plugin</ artifactId > < version >3.8.0</ version > < configuration > < source >1.8</ source > < target >1.8</ target > </ configuration > </ plugin > < plugin > < artifactid >maven-war-plugin</ artifactId > < version >3.2.3</ version > < configuration > < warsourcedirectory >WebContent</ warSourceDirectory > </ configuration > </ plugin > </ plugins > </ build > </ project > |
3. Agregar dependencias
javax.servlet-api: para trabajar con serlvets
mysql-connector-java: driver de conexión mysql
commons-dbcp2: para trabajar con pool de conexiones
jstl: para trabajar con lenguaje de expresiones
Para agregar estas dependencias podemos hacerla directamente desde la IDE de Eclipse o desde el repositorio de Maven. En ambos acasos solo tenemos que buscar el nombre del recurso que estamos queriendo agregar y seleccionar una determinada versión.
Debemos copiar el código de la dependencia y agregarlo al archivo pom.xml de nuestro proyecto de la siguiente manera:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelversion >4.0.0</ modelVersion > < groupid >Crud-Java</ groupId > < artifactid >Crud-Java</ artifactId > < version >0.0.1-SNAPSHOT</ version > < packaging >war</ packaging > < build > < sourcedirectory >src</ sourceDirectory > < plugins > < plugin > < artifactid >maven-compiler-plugin</ artifactId > < version >3.8.0</ version > < configuration > < source >1.8</ source > < target >1.8</ target > </ configuration > </ plugin > < plugin > < artifactid >maven-war-plugin</ artifactId > < version >3.2.3</ version > < configuration > < warsourcedirectory >WebContent</ warSourceDirectory > </ configuration > </ plugin > </ plugins > </ build > <!-- Dependencias --> < dependencies > < dependency > < groupid >javax.servlet</ groupId > < artifactid >javax.servlet-api</ artifactId > < version >3.1.0</ version > < scope >provided</ scope > </ dependency > < dependency > < groupid >mysql</ groupId > < artifactid >mysql-connector-java</ artifactId > < version >8.0.19</ version > </ dependency > < dependency > < groupid >org.apache.commons</ groupId > < artifactid >commons-dbcp2</ artifactId > < version >2.7.0</ version > </ dependency > < dependency > < groupid >javax.servlet</ groupId > < artifactid >jstl</ artifactId > < version >1.2</ version > </ dependency > </ dependencies > </ project > |
El otro modo es agregando las dependencias directamente en Eclipse, para ello, debemos hacer clic en el botón Add... y escribir el nombre de la librería.
Guardamos los cambios y si fuese necesario hacemos clic derecho al proyecto Maven/Update Project, esto para actualizar el proyecto y descargar las librerías si no se descargaron.
2) Creamos la pagina index.jsp y ejecutamos el proyecto
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < title >Menú de Opciones</ title > </ head > < body > < h1 > Menu de Opciones Productos</ h1 > </ body > </ html > |
4. Crear la estructura del proyecto
1) Creamos lo siguientes paquetescom.aprendec.coneion: aquí estará nuestra conexión
com.aprendec.model: aquí irán los DTOs
com.aprendec.dao: aquí irán nuestros DAOs
com.aprendec.controller: aquí irán nuestros servlets
5. Crear la conexión a una base de datos MySQL
1) Crear la tabla productos1 2 3 4 5 6 7 8 9 | CREATE TABLE productos( id int NOT NULL AUTO_INCREMENT, nombre varchar (255) NULL , cantidad decimal (5,2) NULL , precio decimal (5,2) NULL , fecha_crear date NULL , fecha_actualizar date NULL , PRIMARY KEY (id) ); |
2) Crear la clase Conexion.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.aprendec.conexion; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; public class Conexion { private static BasicDataSource dataSource = null ; private static DataSource getDataSource() { if (dataSource == null ) { dataSource = new BasicDataSource(); dataSource.setDriverClassName( "com.mysql.cj.jdbc.Driver" ); dataSource.setUsername( "root" ); dataSource.setPassword( "root" ); dataSource.setInitialSize( 20 ); dataSource.setMaxIdle( 15 ); dataSource.setMaxTotal( 20 ); dataSource.setMaxWaitMillis( 5000 ); } return dataSource; } public static Connection getConnection() throws SQLException { return getDataSource().getConnection(); } } |
6. Crear el modelo
1) Crear la clase Producto.java con sus propiedades, constructores y métodos de acceso getters and setters1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | package com.aprendec.model; import java.sql.Date; public class Producto { private int id; private String nombre; private double cantidad; private double precio; private Date fechaCrear; private Date fechaActualizar; public Producto( int id, String nombre, double cantidad, double precio, Date fechaCrear, Date fechaActualizar) { super (); this .id = id; this .nombre = nombre; this .cantidad = cantidad; this .precio = precio; this .fechaCrear = fechaCrear; this .fechaActualizar = fechaActualizar; } public Producto() { // TODO Auto-generated constructor stub } public int getId() { return id; } public void setId( int id) { this .id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this .nombre = nombre; } public double getCantidad() { return cantidad; } public void setCantidad( double cantidad) { this .cantidad = cantidad; } public double getPrecio() { return precio; } public void setPrecio( double precio) { this .precio = precio; } public Date getFechaCrear() { return fechaCrear; } public void setFechaCrear(Date fechaCrear) { this .fechaCrear = fechaCrear; } public Date getFechaActualizar() { return fechaActualizar; } public void setFechaActualizar(Date fechaActualizar) { this .fechaActualizar = fechaActualizar; } @Override public String toString() { return "Producto [id=" + id + ", nombre=" + nombre + ", cantidad=" + cantidad + ", precio=" + precio + ", fechaCrear=" + fechaCrear + ", fechaActualizar=" + fechaActualizar + "]" ; } } |
7. Crear el DAO
1) Crear la clase ProductoDAO.java con los métodos para el CRUD
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | package com.aprendec.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.aprendec.conexion.Conexion; import com.aprendec.model.Producto; public class ProductoDAO { private Connection connection; private PreparedStatement statement; private boolean estadoOperacion; // guardar producto public boolean guardar(Producto producto) throws SQLException { String sql = null ; estadoOperacion = false ; connection = obtenerConexion(); try { connection.setAutoCommit( false ); sql = "INSERT INTO productos (id, nombre, cantidad, precio, fecha_crear,fecha_actualizar) VALUES(?,?,?,?,?,?)" ; statement = connection.prepareStatement(sql); statement.setString( 1 , null ); statement.setString( 2 , producto.getNombre()); statement.setDouble( 3 , producto.getCantidad()); statement.setDouble( 4 , producto.getPrecio()); statement.setDate( 5 , producto.getFechaCrear()); statement.setDate( 6 , producto.getFechaActualizar()); estadoOperacion = statement.executeUpdate() > 0 ; connection.commit(); statement.close(); connection.close(); } catch (SQLException e) { connection.rollback(); e.printStackTrace(); } return estadoOperacion; } // editar producto public boolean editar(Producto producto) throws SQLException { String sql = null ; estadoOperacion = false ; connection = obtenerConexion(); try { connection.setAutoCommit( false ); sql = "UPDATE productos SET nombre=?, cantidad=?, precio=?, fecha_actualizar=? WHERE id=?" ; statement = connection.prepareStatement(sql); statement.setString( 1 , producto.getNombre()); statement.setDouble( 2 , producto.getCantidad()); statement.setDouble( 3 , producto.getPrecio()); statement.setDate( 4 , producto.getFechaActualizar()); statement.setInt( 5 , producto.getId()); estadoOperacion = statement.executeUpdate() > 0 ; connection.commit(); statement.close(); connection.close(); } catch (SQLException e) { connection.rollback(); e.printStackTrace(); } return estadoOperacion; } // eliminar producto public boolean eliminar( int idProducto) throws SQLException { String sql = null ; estadoOperacion = false ; connection = obtenerConexion(); try { connection.setAutoCommit( false ); sql = "DELETE FROM productos WHERE id=?" ; statement = connection.prepareStatement(sql); statement.setInt( 1 , idProducto); estadoOperacion = statement.executeUpdate() > 0 ; connection.commit(); statement.close(); connection.close(); } catch (SQLException e) { connection.rollback(); e.printStackTrace(); } return estadoOperacion; } // obtener lista de productos public List<producto> obtenerProductos() throws SQLException { ResultSet resultSet = null ; List<producto> listaProductos = new ArrayList<>(); String sql = null ; estadoOperacion = false ; connection = obtenerConexion(); try { sql = "SELECT * FROM productos" ; statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(sql); while (resultSet.next()) { Producto p = new Producto(); p.setId(resultSet.getInt( 1 )); p.setNombre(resultSet.getString( 2 )); p.setCantidad(resultSet.getDouble( 3 )); p.setPrecio(resultSet.getDouble( 4 )); p.setFechaCrear(resultSet.getDate( 5 )); p.setFechaActualizar(resultSet.getDate( 6 )); listaProductos.add(p); } } catch (SQLException e) { e.printStackTrace(); } return listaProductos; } // obtener producto public Producto obtenerProducto( int idProducto) throws SQLException { ResultSet resultSet = null ; Producto p = new Producto(); String sql = null ; estadoOperacion = false ; connection = obtenerConexion(); try { sql = "SELECT * FROM productos WHERE id =?" ; statement = connection.prepareStatement(sql); statement.setInt( 1 , idProducto); resultSet = statement.executeQuery(); if (resultSet.next()) { p.setId(resultSet.getInt( 1 )); p.setNombre(resultSet.getString( 2 )); p.setCantidad(resultSet.getDouble( 3 )); p.setPrecio(resultSet.getDouble( 4 )); p.setFechaCrear(resultSet.getDate( 5 )); p.setFechaActualizar(resultSet.getDate( 6 )); } } catch (SQLException e) { e.printStackTrace(); } return p; } // obtener conexion pool private Connection obtenerConexion() throws SQLException { return Conexion.getConnection(); } } |
8. Crear el servlet controlador
1) Crear la clase ProductoController.java con sus respectivos métodos doGet() y doPost() para administrar las peticiones para la tabla productos
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | package com.aprendec.controller; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.aprendec.dao.ProductoDAO; import com.aprendec.model.Producto; /** * Servlet implementation class ProductoController */ @WebServlet (description = "administra peticiones para la tabla productos" , urlPatterns = { "/productos" }) public class ProductoController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ProductoController() { super (); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String opcion = request.getParameter( "opcion" ); if (opcion.equals( "crear" )) { System.out.println( "Usted a presionado la opcion crear" ); RequestDispatcher requestDispatcher = request.getRequestDispatcher( "/views/crear.jsp" ); requestDispatcher.forward(request, response); } else if (opcion.equals( "listar" )) { ProductoDAO productoDAO = new ProductoDAO(); List<producto> lista = new ArrayList<>(); try { lista = productoDAO.obtenerProductos(); for (Producto producto : lista) { System.out.println(producto); } request.setAttribute( "lista" , lista); RequestDispatcher requestDispatcher = request.getRequestDispatcher( "/views/listar.jsp" ); requestDispatcher.forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println( "Usted a presionado la opcion listar" ); } else if (opcion.equals( "meditar" )) { int id = Integer.parseInt(request.getParameter( "id" )); System.out.println( "Editar id: " + id); ProductoDAO productoDAO = new ProductoDAO(); Producto p = new Producto(); try { p = productoDAO.obtenerProducto(id); System.out.println(p); request.setAttribute( "producto" , p); RequestDispatcher requestDispatcher = request.getRequestDispatcher( "/views/editar.jsp" ); requestDispatcher.forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (opcion.equals( "eliminar" )) { ProductoDAO productoDAO = new ProductoDAO(); int id = Integer.parseInt(request.getParameter( "id" )); try { productoDAO.eliminar(id); System.out.println( "Registro eliminado satisfactoriamente..." ); RequestDispatcher requestDispatcher = request.getRequestDispatcher( "/index.jsp" ); requestDispatcher.forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String opcion = request.getParameter( "opcion" ); Date fechaActual = new Date(); if (opcion.equals( "guardar" )) { ProductoDAO productoDAO = new ProductoDAO(); Producto producto = new Producto(); producto.setNombre(request.getParameter( "nombre" )); producto.setCantidad(Double.parseDouble(request.getParameter( "cantidad" ))); producto.setPrecio(Double.parseDouble(request.getParameter( "precio" ))); producto.setFechaCrear( new java.sql.Date(fechaActual.getTime())); try { productoDAO.guardar(producto); System.out.println( "Registro guardado satisfactoriamente..." ); RequestDispatcher requestDispatcher = request.getRequestDispatcher( "/index.jsp" ); requestDispatcher.forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (opcion.equals( "editar" )) { Producto producto = new Producto(); ProductoDAO productoDAO = new ProductoDAO(); producto.setId(Integer.parseInt(request.getParameter( "id" ))); producto.setNombre(request.getParameter( "nombre" )); producto.setCantidad(Double.parseDouble(request.getParameter( "cantidad" ))); producto.setPrecio(Double.parseDouble(request.getParameter( "precio" ))); producto.setFechaActualizar( new java.sql.Date(fechaActual.getTime())); try { productoDAO.editar(producto); System.out.println( "Registro editado satisfactoriamente..." ); RequestDispatcher requestDispatcher = request.getRequestDispatcher( "/index.jsp" ); requestDispatcher.forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // doGet(request, response); } } |
Hasta aquí hemos terminado toda parte de Java
9. Crear los JSPs
1) Crear las siguientes páginas dentro de la carpeta WebContent/views
crear.jsp: interfaz para crear un nuevo producto
listar.jsp: interfaz para listar los productos
editar.jsp: interfaz para actualizar un producto
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < title >Menú de Opciones</ title > </ head > < body > < h1 >Menu de Opciones Productos</ h1 > < table border = "1" > < tr > < td >< a href = "productos?opcion=crear" > Crear un Producto</ a ></ td > </ tr > < tr > < td >< a href = "productos?opcion=listar" > Listar Productos</ a ></ td > </ tr > </ table > </ body > </ html > |
3) Editar la página crear.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < title >Crear Producto</ title > </ head > < body > < h1 >Crear Producto</ h1 > < form action = "productos" method = "post" > < input type = "hidden" name = "opcion" value = "guardar" > < table border = "1" > < tr > < td >Nombre:</ td > < td >< input type = "text" name = "nombre" size = "50" ></ td > </ tr > < tr > < td >Cantidad:</ td > < td >< input type = "text" name = "cantidad" size = "50" ></ td > </ tr > < tr > < td >Precio:</ td > < td >< input type = "text" name = "precio" size = "50" ></ td > </ tr > </ table > < input type = "submit" value = "Guardar" > </ form > </ body > </ html > |
4) Editar la página listar.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < title >Listar Productos</ title > </ head > < body > < h1 >Listar Productos</ h1 > < table border = "1" > < tr > < td >Id</ td > < td >Nombre</ td > < td >Cantidad</ td > < td >Precio</ td > < td >Fecha Creacion</ td > < td >Fecha Actualizacion</ td > < td >Accion</ td > </ tr > < c:forEach var = "producto" items = "${lista}" > < tr > < td > < a href = "productos?opcion=meditar&id=<c:out value=" ${ producto.id}"></ c:out >"> < c:out value = "${ producto.id}" ></ c:out > </ a > </ td > < td >< c:out value = "${ producto.nombre}" ></ c:out ></ td > < td >< c:out value = "${ producto.cantidad}" ></ c:out ></ td > < td >< c:out value = "${ producto.precio}" ></ c:out ></ td > < td >< c:out value = "${ producto.fechaCrear}" ></ c:out ></ td > < td >< c:out value = "${ producto.fechaActualizar}" ></ c:out ></ td > < td > < a href = "productos?opcion=eliminar&id=<c:out value=" ${ producto.id}"></ c:out >"> Eliminar </ a > </ td > </ tr > </ c:forEach > </ table > </ body > </ html > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=ISO-8859-1" > <title>Editar Producto</title> </head> <body> <h1>Editar Producto</h1> <form action= "productos" method= "post" > <c:set var= "producto" value= "${producto}" ></c:set> <input type= "hidden" name= "opcion" value= "editar" > <input type= "hidden" name= "id" value= "${producto.id}" > <table border= "1" > <tr> <td>Nombre:</td> <td><input type= "text" name= "nombre" size= "50" value= "${producto.nombre}" ></td> </tr> <tr> <td>Cantidad:</td> <td><input type= "text" name= "cantidad" size= "50" value= "${producto.cantidad}" ></td> </tr> <tr> <td>Precio:</td> <td><input type= "text" name= "precio" size= "50" value= "${producto.precio}" ></td> </tr> </table> <input type= "submit" value= "Guardar" > </form> </body> </html> |
10. Ejecutar la Aplicación y probar las funcionalidades
Estructura final de proyecto
Descargar ejercicio
Descargar archivo
Disculpa tengo un problema. Lo que sucede es que a la hora de usar el forEach no muestra nada, es decir toda la estructura que esta dentro del foreach no aparece en la pagina web. Estoy buscando una solucion desde hace días pero no encuentro.
ResponderBorrar¿Podrias ayudarme?
¡Que extraño! Publica tu código para revisarlo. Revisa que estés llamando a los atributos en el EL. Descarga el demo.
BorrarHola, una pregunta el banco de datos lo creas en MySQL Workbench? Y utilizaste Xampp o descargaste el Tomcat?
ResponderBorrarEstamos usando el motor de base de datos MySQL, puede usar Workbench o línea de comandos para crear la base de datos. Usamos Apache Tomcat como contenedor de servlets. No necesitas Xampp, basta con que tengas el Tomcat descomprimido y el MySQL Server. Saludos.
BorrarHola necesito ayuda con el proyecto, al momento de darle listar no muestra nada, ¿podrías ayudarme a verificar mi código?
ResponderBorrar