Ejemplo de aplicación Spring Web MVC
En este post aprenderemos a crear un CRUD Java Web usando Spring MVC, Bootstrap y JDBC en el IDE NetBeans.
1. Crear la base de datos
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | CREATE DATABASE spring_mvc; USE spring_mvc; CREATE TABLE `persona` ( `Id` int (11) unsigned NOT NULL AUTO_INCREMENT, `Nombres` varchar (244) DEFAULT NULL , `Correo` varchar (244) DEFAULT NULL , `Nacionalidad` varchar (244) DEFAULT NULL , PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8; INSERT INTO `persona` (`Nombres`, `Correo`, `Nacionalidad`) VALUES ( 'Leonel Messi' , 'leonelmessi@gmail.com' , 'Argentina' ), ( 'Cristiano Ronaldo' , 'cristianoronaldo@gmail.com' , 'Portugal' ), ( 'Ronaldinho Gaucho' , 'ronaldinhogr@gmail.com' , 'Brasil' ), ( 'Pablo Guerrero' , 'pabloguerrero@gmail.com' , 'Peru' ); |
2. Configurar el proyecto Spring Web MVC
Clic en File/New Project/Java Web/Web Application.
3. Agregamos las librerías necesarias
Clic derecho en la carpeta Libraries/Add Library
Solo necesitaremos el jar de conexión MySQL
4. Creamos la conexión a nuestra base de datos
Para ello creamos la clase Conexión.java dentro del paquete
config.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package config; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class Conexion { public DriverManagerDataSource Conectar(){ DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName( "com.mysql.cj.jdbc.Driver" ); dataSource.setUrl( "jdbc:mysql://localhost:3306/spring_mvc?autoReconnect=true&useSSL=false&useTimezone=true&serverTimezone=UTC" ); dataSource.setUsername( "root" ); dataSource.setPassword( "root" ); return dataSource; } } |
5. Creamos el controlador
Nota: Cada vez que creemos un controlador debemos configurarlo en el
archivo dispatcher-servlet.xml. Para ello, debemos crear nuevos beans para hacer referencia al
controlador que estamos creando.
Controlador.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 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 | package controller; import config.Conexion; import entidad.Persona; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class Controlador { Conexion conexion = new Conexion(); JdbcTemplate jdbcTemplate = new JdbcTemplate(conexion.Conectar()); ModelAndView modelAndView = new ModelAndView(); List datos; int id; @RequestMapping ( "index.htm" ) public ModelAndView listar(){ String sql = "select * from persona" ; datos = this .jdbcTemplate.queryForList(sql); modelAndView.addObject( "lista" , datos); modelAndView.setViewName( "index" ); return modelAndView; } @RequestMapping (value = "agregar.htm" , method = RequestMethod.GET) public ModelAndView agregar(){ modelAndView.addObject( new Persona()); modelAndView.setViewName( "agregar" ); return modelAndView; } @RequestMapping (value = "agregar.htm" , method = RequestMethod.POST) public ModelAndView agregar(Persona persona){ String sql = "insert into persona (Nombres, Correo, Nacionalidad) values (?,?,?)" ; this .jdbcTemplate.update(sql, persona.getNombre(), persona.getCorreo(), persona.getNacionalidad()); return new ModelAndView( "redirect:/index.htm" ); } @RequestMapping (value= "editar.htm" , method = RequestMethod.GET) public ModelAndView Editar(HttpServletRequest request){ id = Integer.parseInt(request.getParameter( "id" )); String sql = "select * from persona where id = " + id; datos = this .jdbcTemplate.queryForList(sql); modelAndView.addObject( "lista" , datos); modelAndView.setViewName( "editar" ); return modelAndView; } @RequestMapping (value = "editar.htm" , method = RequestMethod.POST) public ModelAndView editar(Persona persona){ String sql = "update persona set Nombres=?, Correo=?, Nacionalidad=? where id=?" ; this .jdbcTemplate.update(sql, persona.getNombre(), persona.getCorreo(), persona.getNacionalidad(), persona.getId()); return new ModelAndView( "redirect:/index.htm" ); } @RequestMapping (value = "eliminar.htm" , method = RequestMethod.GET) public ModelAndView eliminar(HttpServletRequest request){ id = Integer.parseInt(request.getParameter( "id" )); String sql = "delete from persona where id = " + id; this .jdbcTemplate.update(sql); return new ModelAndView( "redirect:/index.htm" ); } } |
dispatcher-servlet.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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <? xml version = '1.0' encoding = 'UTF-8' ?> <!-- was: <?xml version="1.0" encoding="UTF-8"?> --> xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> < bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <!-- Most controllers will use the ControllerClassNameHandlerMapping above, but for the index controller we are using ParameterizableViewController, so we must define an explicit mapping for it. --> < bean id = "urlMapping" class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > < property name = "mappings" > < props > <!-- Referencias --> < prop key = "index.htm" >controlador</ prop > < prop key = "agregar.htm" >controlador</ prop > < prop key = "editar.htm" >controlador</ prop > < prop key = "eliminar.htm" >controlador</ prop > </ props > </ property > </ bean > < bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix = "/WEB-INF/jsp/" p:suffix = ".jsp" /> <!-- Controladores. --> < bean name = "controlador" class = "controller.Controlador" /> </ beans > |
6. Crear la entidad
Crear la entidad Persona.java dentro del paquete
entidad.
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 | package entidad; public class Persona { private int id; private String nombre; private String correo; private String nacionalidad; public Persona() { } public Persona( int id, String nombre, String correo, String nacionalidad) { this .id = id; this .nombre = nombre; this .correo = correo; this .nacionalidad = nacionalidad; } 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 String getCorreo() { return correo; } public void setCorreo(String correo) { this .correo = correo; } public String getNacionalidad() { return nacionalidad; } public void setNacionalidad(String nacionalidad) { this .nacionalidad = nacionalidad; } } |
7. Crear las páginas
Editar el archivo index.jsp.
Crear el archivo agregar.jsp dentro de la carpeta
jsp.
Crear el arcivo editar.jsp dentro de la carpeta jsp.
gracias eso me ayudo mucho
ResponderBorrarExcelente aporte amigo. Muchas gracias...
ResponderBorrarExcelente proyecto me gustaria si por favor me puedes colaborar con una duda que tengo
ResponderBorrar