Sei sulla pagina 1di 21

Spring-Hibernate Formulario Contactos 1 / 21

Spring – Hibernate Formulario almacenando la


información en Base de Datos
Formulario con Base de Datos MySQL usando anotaciones

Arquitectura de la aplicación

Base de Datos MySQL


/FormasSpringBD3MVC/Contacts.sql
CREATE TABLE Contacts
(
id INT PRIMARY KEY AUTO_INCREMENT,
firstname VARCHAR(30),
lastname VARCHAR(30),
colorCode VARCHAR(30),
profesion VARCHAR(30),
telephone VARCHAR(15),
email VARCHAR(30),
created TIMESTAMP DEFAULT NOW()
);

/FormasSpringBD3MVC/Profesiones.sql
profesionCREATE TABLE Profesion
(
id INT PRIMARY KEY AUTO_INCREMENT,
profesion VARCHAR(30),
created TIMESTAMP DEFAULT NOW()
);
Spring-Hibernate Formulario Contactos 2 / 21
Spring-Hibernate Formulario Contactos 3 / 21

Recursos
/FormasSpringBD3MVC/WebContent/img/contacto.jpg

/FormasSpringBD3MVC/WebContent/img/personas.jpg

Configuración XML
/FormasSpringBD3MVC/WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>FormasSpring3MVC</display-name>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Spring-Hibernate Formulario Contactos 4 / 21

/FormasSpringBD3MVC/src/hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<mapping class="Formas.Contact" />
<mapping class="Formas.Profesion" />
</session-factory>
</hibernate-configuration>

/FormasSpringBD3MVC/WebContent/WEB-INF/spring-servlet.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
<context:component-scan base-package="Control" />

<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Spring-Hibernate Formulario Contactos 5 / 21

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"


destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<!-- Hibernate 3 Annotation SessionFactory Bean definition-->


<!-- Esta es una forma de programar el objeto sessionFactory.
En este caso no se requiere classpath:hibernate.cfg.xml
<bean id="hibernate3AnnotatedSessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>Formas.Contact</value>
<value>Formas.Profesion</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="contactDAO" class="dao.ContactDAOImpl">


<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
</bean>
-->
<!-- Esta es otra forma de programar el objeto sessionFactory.
En este caso sí se requiere classpath:hibernate.cfg.xml -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
Spring-Hibernate Formulario Contactos 6 / 21

<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="contactDAO" class="dao.ContactDAOImpl">


<property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="contactService" class="servicio.ContactServiceImpl"/>


</beans>

/FormasSpringBD3MVC/WebContent/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Ejemplo Spring3 MVC"/>

Archivos Properties
/FormasSpringBD3MVC/WebContent/WEB-INF/jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=admin

/FormasSpringBD3MVC/src/messages_es_MX.properties
label.firstname=Nombre
label.lastname=Apellido
label.Color=Color
label.email=Email
label.telephone=Tel&#233;fono
label.addcontact=Agregar Contacto
label.Lista=Lista de Contactos
label.title=Administrador de Contactos
label.profesion=Profesi&#243;n
Spring-Hibernate Formulario Contactos 7 / 21

Beans
/FormasSpringBD3MVC/src/Formas/Color.java
package Formas;

public class Color {

private String colorName;


private String colorCode;

public Color() {}

public Color( String colorName, String colorCode ) {


this.colorName = colorName;
this.colorCode = colorCode;
}
public String getColorName() {
return colorName;
}
public void setColorName( String colorName ) {
this.colorName = colorName;
}
public String getColorCode() {
return colorCode;
}
public void setColorCode( String colorCode ) {
this.colorCode = colorCode;
}
}

/FormasSpringBD3MVC/src/Formas/Profesion.java
package Formas;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table( name="Profesion" )
public class Profesion {

@Id
@Column( name="id" )
@GeneratedValue
private Integer id;
Spring-Hibernate Formulario Contactos 8 / 21

@Column( name="profesion" )
private String profesion;

public Profesion() {}

public Profesion( String profesion ) {


this.profesion = profesion;
}

public String getProfesion() {


return profesion;
}

public void setProfesion(String profesion) {


this.profesion = profesion;
}
}
/FormasSpringBD3MVC/src/Formas/Contact.java
package Formas;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table( name="Contacts" )
public class Contact {

@Id
@Column( name="id" )
@GeneratedValue
private Integer id;

@Column( name="firstname" )
private String firstname;

@Column( name="lastname" )
private String lastname;

@Column( name="profesion" )
private String profesion;
Spring-Hibernate Formulario Contactos 9 / 21

@Column( name="colorCode" )
private String colorCode;

@Column( name="email" )
private String email;

@Column( name="telephone" )
private String telephone;

public void setFirstname( String firstname ) {


this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setLastname( String lastname ) {
this.lastname = lastname;
}
public String getLastname() {
return lastname;
}
public void setColorCode( String colorCode ) {
this.colorCode = colorCode;
}
public String getColorCode() {
return colorCode;
}
public void setProfesion( String profesion ) {
this.profesion = profesion;
}
public String getProfesion() {
return profesion;
}
public void setEmail( String email ) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setTelephone( String telephone ) {
this.telephone = telephone;
}
public String getTelephone() {
return telephone;
}
Spring-Hibernate Formulario Contactos 10 / 21

public void setId( Integer id ) {


this.id = id;
}
public Integer getId() {
return id;
}
}

Vistas
/FormasSpringBD3MVC/WebContent/index.jsp
<%@ 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>Spring 3.0 MVC Uso de Formas</title>
</head>
<body>
<jsp:forward page="contactos.html"></jsp:forward>
</body>
</html>

/FormasSpringBD3MVC/WebContent/WEB-INF/jsp/contact.jsp
<%@ 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">

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>


<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Administrador de Contactos</title>
<style type="text/css">
body {
font-family: sans-serif;
}
.data, .data td {
border-collapse: collapse;
width: 10%;
border: 1px solid #aaa;
margin: 2px;
padding: 2px;
}
Spring-Hibernate Formulario Contactos 11 / 21

.data th {
font-weight: bold;
background-color: #5C82FF;
color: white;
}
</style>
</head>
<body>

<h2><spring:message code="label.title"/></h2>

<form:form method="post" action="add.html" commandName="contact" >

<table>
<tr>
<td>
<table>
<tr>
<td><form:label path="firstname"><spring:message
code="label.firstname"/></form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname"><spring:message
code="label.lastname"/></form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="profesion"><spring:message
code="label.profesion"/></form:label></td>
<td>
<form:select path="profesion">
<form:option value="" label="--Please Select"/>
<form:options items="${profesionlist}" itemValue="profesion"
itemLabel="profesion"/>
</form:select>
</td>
</tr>
<tr>
<td><spring:message code="label.Color"/></td>
<td>
<form:select path="colorCode">
<form:option value="" label="--Please Select"/>
<form:options items="${colorlist}" itemValue="colorCode"
itemLabel="colorName"/>
</form:select>
</td>
</tr>
<tr>
<td><form:label path="email"><spring:message
code="label.email"/></form:label></td>
<td><form:input path="email" /></td>
</tr>
Spring-Hibernate Formulario Contactos 12 / 21

<tr>
<td><form:label path="telephone"><spring:message
code="label.telephone"/></form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2" align="center" >
<br>
<input type="submit" value="<spring:message
code="label.addcontact"/>"/>
</td>
</tr>

</table>
</td>
<td>
<img src="${pageContext.request.contextPath}/img/contacto.jpg"
title="Contactos"/>
</td>
</tr>
</table>
</form:form>

<c:if test="${!empty contactList}">


<h3><spring:message code="label.Lista"/></h3>
<table class="data">
<tr>
<th>No</th>
<th><spring:message code="label.firstname"/></th>
<th><spring:message code="label.lastname"/></th>
<th><spring:message code="label.profesion"/></th>
<th><spring:message code="label.Color"/></th>
<th><spring:message code="label.email"/></th>
<th><spring:message code="label.telephone"/></th>
<th>&nbsp;</th>
</tr>
<c:forEach items="${contactList}" var="contact" varStatus="status">
<tr>
<td align="center">${status.count}</td>
<td><input name="contactList[${status.index}].firstname"
value="${contact.firstname}"/></td>
<td><input name="contactList[${status.index}].lastname"
value="${contact.lastname}"/></td>
<td><input name="contactList[${status.index}].profesion"
value="${contact.profesion}"/></td>

<td><input name="contactList[${status.index}].colorCode"
value="${contact.colorCode}"/></td>
<td><input name="contactList[${status.index}].email"
value="${contact.email}"/></td>
<td><input name="contactList[${status.index}].telephone"
value="${contact.telephone}"/></td>
Spring-Hibernate Formulario Contactos 13 / 21

<td><a href="delete/${contact.id}.html"
onclick="return confirm('¿ Estás seguro que deseas borrar este contacto ?')">
Eliminar</a></td>
</tr>
</c:forEach>
</table>
</c:if>
<br>
<center> <img src="data:image/jpeg;base64,${image}" alt="..." width="150"
height="100"></center>
</body>
</html>

Control
/FormasSpringBD3MVC/src/Control/ControlForma.java
package Control;

import java.io.IOException;
import java.util.Map;

import Formas.Contact;
import servicio.ContactService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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;

@Controller
public class ControlForma {

private ContactService contactService;

@Autowired
public ControlForma( ContactService contactService) {
this.contactService = contactService;
}

@RequestMapping( "/contactos.html" )
public String listContacts( Map<String, Object> map ) throws IOException {

map.put( "contact", new Contact() );


map.put( "contactList", contactService.listContact() );
Spring-Hibernate Formulario Contactos 14 / 21

map.put( "colorlist", contactService.listColor() );


map.put( "profesionlist", contactService.listProfesion() );
map.put( "image", contactService.imagen());

return "contact";
}

@RequestMapping( value = "/add.html", method = RequestMethod.POST )


public String addContact( @ModelAttribute("contact") Contact contact,
BindingResult result ) {

contactService.addContact( contact );
return "redirect:/contactos.html";
}

@RequestMapping( value = "/delete/{contactId}.html", method = RequestMethod.GET )


public String deleteContact( @PathVariable( "contactId" ) Integer contactId ) {

contactService.removeContact( contactId );
return "redirect:/contactos.html";
}
}

Servicios
/FormasSpringBD3MVC/src/servicio/ContactService.java
package servicio;

import java.io.FileNotFoundException;
import java.util.List;

import Formas.Color;
import Formas.Contact;
import Formas.Profesion;

public interface ContactService {

public void addContact( Contact contact );


public List<Contact> listContact();
public List<Color> listColor();
public void removeContact( Integer id );
public List<Profesion> listProfesion();
public String imagen() throws FileNotFoundException ;
}
Spring-Hibernate Formulario Contactos 15 / 21

/FormasSpringBD3MVC/src/servicio/ContactServiceImpl.java
package servicio;

import java.io.FileNotFoundException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dao.ContactDAO;
import Formas.Color;
import Formas.Contact;
import Formas.Profesion;
// @Service
public class ContactServiceImpl implements ContactService {

private ContactDAO contactDAO;


@Autowired
public ContactServiceImpl( ContactDAO contactDAO ) {
this.contactDAO = contactDAO;
}
// @Transactional
public void addContact( Contact contact ) {
contactDAO.addContact( contact );
}
// @Transactional
public List<Contact> listContact() {
return contactDAO.listContact();
}
// @Transactional
public List<Color> listColor() {
return contactDAO.listColor();
}
// @Transactional
public void removeContact( Integer id ) {
contactDAO.removeContact(id);
}
// @Transactional
public List<Profesion> listProfesion() {
return contactDAO.listProfesion();
}
// @Transactional
public String imagen() throws FileNotFoundException {
return contactDAO.imagen();
}
}
Spring-Hibernate Formulario Contactos 16 / 21

Clases de Acceso a la Base de Datos


/FormasSpringBD3MVC/src/dao/ContactDAO.java
package dao;

import java.io.FileNotFoundException;
import java.util.List;

import Formas.Color;
import Formas.Contact;
import Formas.Profesion;

public interface ContactDAO {

public void addContact( Contact contact );


public List<Contact> listContact();
public List<Color> listColor();
public void removeContact( Integer id );
public List<Profesion> listProfesion();
public String imagen() throws FileNotFoundException;
}
/FormasSpringBD3MVC/src/dao/ContactDAOImpl.java
package dao;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import Formas.Color;
import Formas.Contact;
import Formas.Profesion;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
Spring-Hibernate Formulario Contactos 17 / 21

// @Repository
public class ContactDAOImpl implements ContactDAO {

private SessionFactory sessionFactory;

public void setSessionFactory( SessionFactory sessionFactory ) {


this.sessionFactory = sessionFactory;
}

public void addContact( Contact contact ) {

try {
Session session = this.sessionFactory.openSession();
Transaction transact = session.beginTransaction();
try {
session.save(contact);
transact.commit();
}
catch ( HibernateException e ) {
transact.rollback();
throw e;
}
finally {
session.close();
}
} catch (RuntimeException re) {
throw re;
}
}

public List<Contact> listContact() {

return sessionFactory.openSession().createQuery( "from Contact" ).list();


}
public List<Color> listColor() {

List<Color> colorList = new ArrayList<Color>();


colorList.add( new Color( "Indian Red", "F75D59"));
colorList.add( new Color( "Red", "FF0000"));
colorList.add( new Color( "Salmon", "F9966B"));
colorList.add( new Color( "Lemon Chiffon", "FFF8C6"));
colorList.add( new Color( "Olive Green", "BCE954"));
colorList.add( new Color( "Steel Blue", "C6DEFF"));
colorList.add( new Color( "Medium Purple", "9E7BFF"));
return colorList;
}
Spring-Hibernate Formulario Contactos 18 / 21

public void removeContact( Integer id ) {

try {
Session session = this.sessionFactory.openSession();
Transaction transact = session.beginTransaction();
try {
Contact contact = (Contact) session.load( Contact.class, id );
if ( contact != null ) {
session.delete( contact );
transact.commit();
}
}
catch ( HibernateException e ) {
transact.rollback();
throw e;
}
finally {
session.close();
}

} catch (RuntimeException re) {


throw re;
}
}

public List<Profesion> listProfesion() {

return sessionFactory.openSession().
createQuery( "from Profesion order by profesion" ).list();
}

public String imagen() throws FileNotFoundException {

try {
File file = new File("C:\\img\\personas.jpg");
// File file = new File( context.request.getContextPath() +
"\\img\\contacto.jpg");
FileInputStream fis = new FileInputStream( file );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b;
byte[] buffer = new byte[ 1024 ];
byte[] fileBytes = new byte[ 1024 ] ;
try {
while (( b = fis.read(buffer) ) != -1 )
bos.write( buffer, 0, b );
fileBytes = bos.toByteArray();
fis.close();
bos.close();
Spring-Hibernate Formulario Contactos 19 / 21

} catch ( IOException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String encoded = Base64.encode( fileBytes );
String encodedString = new String( encoded );

return encodedString;
} catch ( FileNotFoundException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}

http://localhost:8080/FormasSpringBD3MVC/
Spring-Hibernate Formulario Contactos 20 / 21
Spring-Hibernate Formulario Contactos 21 / 21

Potrebbero piacerti anche