martes, 21 de febrero de 2017

Realizando un Crud con Spring MVC, MySQL y Bootstrap

Spring MVC CRUD Ejemplo:

CRUD (crear, leer, actualizar y eliminar) es la aplicación más importante para la creación de cualquier proyecto. Proporciona una idea para desarrollar un gran proyecto. En Spring MVC, podemos desarrollar una sencilla aplicación un CRUD. 

Aquí estamos utilizando el JdbcTemplate de interacción con la base de datos.
el motor de base de datos que se utiliza es MySql:

Ejemplo CRUD

Crear un table "crudspring" en una base de datos MySql con los siguientes campos: id es autoincrementable , name, salary, designation.

la base de datos que se uso para esta prueba fue MySQL "prueba" y la tabla "crudspring":

IDE: Spring Tool Suite o pueden utilizar Eclipse

En las siguientes imágenes veremos el paso a paso del proyecto usando spring mvc y mysql:

El enlace del proyecto se estará dejando al final de la página:


 Emp.java
package com.cloudsrcsoft.beans;

public class Emp {
 private int id;
 private String name;
 private float salary;
 private String designation;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public float getSalary() {
  return salary;
 }

 public void setSalary(float salary) {
  this.salary = salary;
 }

 public String getDesignation() {
  return designation;
 }

 public void setDesignation(String designation) {
  this.designation = designation;
 }

}


EmpDao.java
package com.cloudsrcsoft.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.cloudsrcsoft.beans.Emp;

public class EmpDao {
 JdbcTemplate template;

 public void setTemplate(JdbcTemplate template) {
  this.template = template;
 }

 public int save(Emp p) {
  String sql = "insert into crudspring(name,salary,designation) values('" + p.getName() + "'," + p.getSalary()
    + ",'" + p.getDesignation() + "')";
  return template.update(sql);
 }

 public int update(Emp p) {
  String sql = "update crudspring set name='" + p.getName() + "', salary=" + p.getSalary() + ", designation='"
    + p.getDesignation() + "' where id=" + p.getId() + "";
  return template.update(sql);
 }

 public int delete(int id) {
  String sql = "delete from crudspring where id=" + id + "";
  return template.update(sql);
 }

 public Emp getEmpById(int id) {
  String sql = "select * from crudspring where id=?";
  return template.queryForObject(sql, new Object[] { id }, new BeanPropertyRowMapper<Emp>(Emp.class));
 }

 public List<Emp> getEmployees() {
  return template.query("select * from crudspring", new RowMapper<Emp>() {
   public Emp mapRow(ResultSet rs, int row) throws SQLException {
    Emp e = new Emp();
    e.setId(rs.getInt(1));
    e.setName(rs.getString(2));
    e.setSalary(rs.getFloat(3));
    e.setDesignation(rs.getString(4));
    return e;
   }
  });
 }
}




 EmpController.java

package com.cloudsrcsoft.springmvc;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.cloudsrcsoft.beans.Emp;
import com.cloudsrcsoft.dao.EmpDao;

@Controller
public class EmpController {
 @Autowired
 EmpDao dao;

 @RequestMapping("/empform")
 public ModelAndView showform() {
  return new ModelAndView("empform", "command", new Emp());
 }

 @RequestMapping(value = "/save", method = RequestMethod.POST)
 public ModelAndView save(@ModelAttribute("emp") Emp emp) {
  dao.save(emp);
  return new ModelAndView("redirect:/viewemp");
 }

 @RequestMapping("/viewemp")
 public ModelAndView viewemp() {
  List<Emp> list = dao.getEmployees();
  return new ModelAndView("viewemp", "list", list);
 }

 @RequestMapping(value = "/editemp/{id}")
 public ModelAndView edit(@PathVariable int id) {
  Emp emp = dao.getEmpById(id);
  return new ModelAndView("empeditform", "command", emp);
 }

 @RequestMapping(value = "/editsave", method = RequestMethod.POST)
 public ModelAndView editsave(@ModelAttribute("emp") Emp emp) {
  dao.update(emp);
  return new ModelAndView("redirect:/viewemp");
 }

 @RequestMapping(value = "/deleteemp/{id}", method = RequestMethod.GET)
 public ModelAndView delete(@PathVariable int id) {
  dao.delete(id);
  return new ModelAndView("redirect:/viewemp");
 }

}

 servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
 
 <!-- Enables the Spring MVC @Controller programming model -->
 <annotation-driven />

 <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
 <resources mapping="/resources/**" location="/resources/" />

 <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="prefix" value="/WEB-INF/views/" />
  <beans:property name="suffix" value=".jsp" />
 </beans:bean>
 
 <context:component-scan base-package="com.cloudsrcsoft.springmvc" />
 
 
 
</beans:beans>


 root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
 http://www.springframework.org/schema/context  
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/prueba" />
  <property name="username" value="root" />
  <property name="password" value="" />
 </bean>

 <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="ds"></property>
 </bean>

 <bean id="dao" class="com.cloudsrcsoft.dao.EmpDao">
  <property name="template" ref="jt"></property>
 </bean>
</beans>


 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring/root-context.xml</param-value>
 </context-param>
 
 <!-- Creates the Spring Container shared by all Servlets and Filters -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- Processes application requests -->
 <servlet>
  <servlet-name>appServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
  
 <servlet-mapping>
  <servlet-name>appServlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>


 pow.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.cloudsrcsoft</groupId>
 <artifactId>springmvc</artifactId>
 <name>CRUDSpringMVC</name>
 <packaging>war</packaging>
 <version>1.0.0-BUILD-SNAPSHOT</version>
 <properties>
  <java-version>1.6</java-version>
  <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
  <org.aspectj-version>1.6.10</org.aspectj-version>
  <org.slf4j-version>1.6.6</org.slf4j-version>
 </properties>
 <dependencies>
  <!-- Spring -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${org.springframework-version}</version>
   <exclusions>
    <!-- Exclude Commons Logging in favor of SLF4j -->
    <exclusion>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     </exclusion>
   </exclusions>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework-version}</version>
  </dependency>
  
  <!-- Spring JDBC -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
   <!-- MySQL database driver -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.9</version>
  </dependency>
    
  <!-- AspectJ -->
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjrt</artifactId>
   <version>${org.aspectj-version}</version>
  </dependency> 
  
  <!-- Logging -->
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${org.slf4j-version}</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>jcl-over-slf4j</artifactId>
   <version>${org.slf4j-version}</version>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>${org.slf4j-version}</version>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.15</version>
   <exclusions>
    <exclusion>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
    </exclusion>
    <exclusion>
     <groupId>javax.jms</groupId>
     <artifactId>jms</artifactId>
    </exclusion>
    <exclusion>
     <groupId>com.sun.jdmk</groupId>
     <artifactId>jmxtools</artifactId>
    </exclusion>
    <exclusion>
     <groupId>com.sun.jmx</groupId>
     <artifactId>jmxri</artifactId>
    </exclusion>
   </exclusions>
   <scope>runtime</scope>
  </dependency>

  <!-- @Inject -->
  <dependency>
   <groupId>javax.inject</groupId>
   <artifactId>javax.inject</artifactId>
   <version>1</version>
  </dependency>
    
  <!-- Servlet -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
 
  <!-- Test -->
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.7</version>
   <scope>test</scope>
  </dependency>        
 </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 empeditform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
 <title>CRUD SPRING MVC CON MYSQL</title>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
  <div class="row-fluid">
   <div class="col-md-6">
    <h4 class="text-center">Editar Empleado</h4>
    <hr>
    <form:form method="post" action="/springmvc/editsave">
     <form:hidden path="id" />
     <div class="form-group">
      <label for = "name">Nombre: </label>
      <form:input path="name" class="form-control"/>
     </div>
     <div class="form-group">
      <label for = "salary">Salario: </label>
      <form:input path="salary" class="form-control"/>
     </div>
     <div class="form-group">
      <label for ="designation">Designación</label>
      <form:input path="designation" class="form-control"/>
     </div>
     <div class="form-group">
      <input type="submit" value="Editar" class="btn btn-success"/>
     </div>
    </form:form>
   </div>
  </div>
 </div>
</body>
</html>
 empform.jsp
  <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<head>
 <title>CRUD SPRING MVC CON MYSQL</title>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
  <div class="row-fluid">
   <div class="col-md-6">
    <h4 class="text-center">Agregar Nuevo Empleado</h4>
    <hr>
    <form:form method="post" action="save">
     <div class="form-group">
      <label for = "name">Nombre: </label>
      <form:input path="name" class="form-control"/>
     </div>
     <div class="form-group">
      <label for = "salary">Salario: </label>
      <form:input path="salary" class="form-control"/>
     </div>
     <div class="form-group">
      <label for ="designation">Designación</label>
      <form:input path="designation" class="form-control"/>
     </div>
     <div class="form-group">
      <input type="submit" value="Guardar" class="btn btn-success"/>
     </div>
    </form:form>
   </div>
  </div>
 </div>
</body>
</html>

 viewemp.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
 <title>CRUD SPRING MVC CON MYSQL</title>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
 <div class="row-fluid">
  <div class="col-md-6">
   <h4 class="text-center">Lista de Empleados</h4>
   <hr>
   <table class="table table-bordered table-striped">
    <thead>
    <tr>
     <th>Id</th>
     <th>Nombre</th>
     <th>Salario</th>
     <th>Designación</th>
     <th>Editar</th>
     <th>Eliminar</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach var="emp" items="${list}">
     <tr>
      <td>${emp.id}</td>
      <td>${emp.name}</td>
      <td>${emp.salary}</td>
      <td>${emp.designation}</td>
      <td><a href="editemp/${emp.id}" class="btn btn-info btn-xs"><i class="glyphicon glyphicon-check"></i> Editar</a></td>
      <td><a href="deleteemp/${emp.id}" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-trash"></i> Eliminar</a></td>
     </tr>
    </c:forEach>    
    </tbody>
   </table>
   <br />
   <a href="empform" class="btn btn-success"><i class="glyphicon glyphicon-edit"></i> Nuevo Empleado</a>
  </div>
 </div>
</div>
</body>
</html>





Link de descarga Mega: Click Aquí Para Descargar Proyecto Spring MVC
También vea un crud con servlet y JSP: Servlet JSP

4 comentarios:

  1. Muy buen proyecto , sin embargo no esta explicado paso a paso. De todas maneras gracia por tu aporte!

    ResponderEliminar
  2. No puedo descargar el proyecto

    ResponderEliminar
  3. Excelente aportación. Muchas gracias.

    ResponderEliminar