¡Bienvenidos a todos! Esta publicación formará parte de una serie de 10 publicaciones que estaré desarrollando para aprender a crear una aplicación web en Java, bajo la plataforma JEE usando los frameworks de JPA y JSF. Este será un curso en forma de guía para todas aquellas personas que estén empezando en el mundo de la programación web.
En este curso aprenderemos a desarrollar aplicaciones web en N-CAPAS utilizando los patrones de diseño JEE, el estilo arquitectónico MVC y las funcionalidades provistas por los framework JSF (Java Server Faces) a nivel de vista-controlador y por JPA (Java Persistence API) a nivel de persistencia.
Este curso estará dividido en dos partes, En la primera parte, aprenderemos a configurar y utilizar el framework JPA mediante el desarrollo de aplicaciones Stand.Alone. En la segunda parte, aprenderemos a utilizar el framework JSF para desarrollar aplicaciones web. Por último, integraremos las funcionalidades de ambos frameworks en una aplicación final.
En este curso aprenderemos a desarrollar aplicaciones web en N-CAPAS utilizando los patrones de diseño JEE, el estilo arquitectónico MVC y las funcionalidades provistas por los framework JSF (Java Server Faces) a nivel de vista-controlador y por JPA (Java Persistence API) a nivel de persistencia.
Este curso estará dividido en dos partes, En la primera parte, aprenderemos a configurar y utilizar el framework JPA mediante el desarrollo de aplicaciones Stand.Alone. En la segunda parte, aprenderemos a utilizar el framework JSF para desarrollar aplicaciones web. Por último, integraremos las funcionalidades de ambos frameworks en una aplicación final.
APLICACIÓN
Para este ejemplo: Implementaremos un Mantenimiento de Empleados con un logín integrando JSF (Java Server Faces) y JPA (Java Persistence API) donde vamos a aprender a generar entidades a partir de las tablas de base de datos utilizando el Wizard que trae JPA el cual se encargará de aplicar el ORM Mapping o mapeo relacional de objetos a las entidades y generar las estrategias de llave primaria. Asociaremos un entityListener a una entidad con tablas relacionadas, crearemos el PhaseListener para monitorear la ejecución de faces del JSF, emplearemos plantilla faceles, emplearemos archivos de recursos de textos para el cambio de idioma y agregaremos validaciones a las interfaces, es decir todo lo visto en este curso.
1. Pasos para Configurar el proyecto
Paso 1 - Crear un proyecto web dinámico
integrando JSF y JPA.
Vea
el siguiente link para saber como
crear un dynamic web proyect integrado con JSF (Java Server Faces) Y JPA (Java
Persistence API) y Apache Tomcat como servidor web:
Paso 2 - Agregar las librerías básicas en
la carpeta lib del webContent. Si hemos seguidos los pasos de como crear
un dynamic web proyect integrado con JSF (Java Server Faces) Y JPA (Java
Persistence API), no es necesario incluir las librerías de JPA y JSF,
puesto que ya han sido configurado al crear el proyecto desde un
principio. Solo incluiríamos las librerías extras que
usaremos en el proyecto como log4j, mysql.conector, primefaces, etc.
Ahora, si no hemos seguido los pasos de creación del proyecto JSF y JPA, y solo
creamos un dynamic web proyect simple sin integrar JSF y JPA, es
posible configurarlo después, puesto que es obvio que
lo necesitaremos si queremos trabajar con estos frameworks.
Paso 3 - Configurar el Faces Servlet en
el archivo de configuración "web.xml", este archivo es creado al momento de crear
el proyecto.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | < web-app id = "WebApp_ID" version = "3.0" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" > < welcome-file-list > < welcome-file >faces/inicio.xhtml</ welcome-file > </ welcome-file-list > < servlet > < servlet-name >Faces Servlet</ servlet-name > < servlet-class >javax.faces.webapp.FacesServlet</ servlet-class > < load-on-startup >1</ load-on-startup > </ servlet > < servlet-mapping > < servlet-name >Faces Servlet</ servlet-name > < url-pattern >/faces/*</ url-pattern > </ servlet-mapping > </ web-app > |
Paso 4 - Crear el archivo de
configuración "faces-config.xml" dentro de la carpeta WEB-INF para registrar el listener y
el archivo de recursos de texto que posteriormente crearemos, este archivo de
configuración también se crea al momento de crear el proyecto.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | < faces-config version = "2.1" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd" > < lifecycle > < phase-listener >jsf.listener.JSFListener</ phase-listener > </ lifecycle > < application > < resource-bundle > < base-name >pe.edu.cibertec.recursos.textos</ base-name > < var >texto</ var > </ resource-bundle > < message-bundle >pe.edu.cibertec.recursos.textos</ message-bundle > < locale-config > < default-locale >es</ default-locale > < supported-locale >en</ supported-locale > </ locale-config > </ application > </ faces-config > |
2. Crear las clases
Anteriormente, nosotros creábamos las clases entidades manualmente y también aplicábamos la técnica ORM Mapping para asociar las entidades con las tablas de base de datos y para mapearlas utilizábamos anotaciones, el problema era que todo lo teníamos que hacer manualmente, pero ¿qué pasaría si tuviésemos 10, 20, 30 tablas? seria tedioso mapearlas una por una. Pues bueno, eso se acabó, ahora haremos lo mismo pero en pocos segundo empleando el Wizard que nos trae JPA para generar las entidades a partir de las tablas de base de datos. Para ello, si no hemos seguido los pasos de como crear un proyecto web integrado con JSF Y JPA debemos de configurarlo para poder utilizar el Wizard.
Paso 5 - Configurar el Java Persintence API (JPA) en tu proyecto web java
Visitar el siguiente link para saber como configurar un proyecto web simple para el caso de que no tengas integrado las facetas de JPA y JSF. (Opcional)
Paso 6 - Generar las clases entidades a partir de las tablas de base de datos utilizando el wizard de JPA, de esta manera evitamos crear las entidades y mapearlas con las tablas de base de datos de manual.
Visitar el siguiente link para saber como generar entidades a partir de las tablas de base de datos utilizando el Wizard de JPA.
Paso 7 - El Wizard de JPA generará las
entidades relacionadas TbCargo.java, TbCasillero.java,
TbEmpleado.java, TbSecuencia.java, TbUsuario.java en el paquete
persistence.entity.
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 | package persistence.entity; import java.io.Serializable; import javax.persistence.*; import java.util.Set; /** * The persistent class for the tb_cargo database table. * */ @Entity @Table (name = "tb_cargo" ) public class TbCargo implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue (strategy = GenerationType.IDENTITY) @Column (name = "COD_CAR" ) private int codCar; @Column (name = "DES_CAR" ) private String desCar; // bi-directional many-to-one association to TbEmpleado @OneToMany (mappedBy = "tbCargo" ) private Set<tbempleado> tbEmpleados; public TbCargo() { } public int getCodCar() { return this .codCar; } public void setCodCar( int codCar) { this .codCar = codCar; } public String getDesCar() { return this .desCar; } public void setDesCar(String desCar) { this .desCar = desCar; } public Set<tbempleado> getTbEmpleados() { return this .tbEmpleados; } public void setTbEmpleados(Set<tbempleado> tbEmpleados) { this .tbEmpleados = tbEmpleados; } |
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 | package persistence.entity; import java.io.Serializable; import javax.persistence.*; import java.util.Set; /** * The persistent class for the tb_casillero database table. * */ @Entity @Table (name = "tb_casillero" ) public class TbCasillero implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue (strategy = GenerationType.IDENTITY) @Column (name = "COD_CAS" ) private int codCas; @Column (name = "DES_CAS" ) private String desCas; @Column (name = "EST_CAS" ) private String estCas; // bi-directional many-to-one association to TbEmpleado @OneToMany (mappedBy = "tbCasillero" ) private Set<tbempleado> tbEmpleados; public TbCasillero() { } public int getCodCas() { return this .codCas; } public void setCodCas( int codCas) { this .codCas = codCas; } public String getDesCas() { return this .desCas; } public void setDesCas(String desCas) { this .desCas = desCas; } public String getEstCas() { return this .estCas; } public void setEstCas(String estCas) { this .estCas = estCas; } public Set<tbempleado> getTbEmpleados() { return this .tbEmpleados; } public void setTbEmpleados(Set<tbempleado> tbEmpleados) { this .tbEmpleados = tbEmpleados; } } |
. TbEmpleado
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 | package persistence.entity; import java.io.Serializable; import javax.persistence.*; import persistence.entity.listener.TbEmpleadoListener; import java.util.Date; /** * The persistent class for the tb_empleado database table. * */ // Es para mandar las anotaciones del previa a una clase listener @EntityListeners (TbEmpleadoListener. class ) @Entity @Table (name = "tb_empleado" ) public class TbEmpleado implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue (strategy = GenerationType.IDENTITY) @Column (name = "COD_EMP" ) private Integer codEmp; @Column (name = "APE_EMP" ) private String apeEmp; @Column (name = "ARE_EMP" ) private String areEmp; @Column (name = "EDA_EMP" ) private int edaEmp; @Temporal (TemporalType.DATE) @Column (name = "FEC_ING_EMP" ) private Date fecIngEmp; @Column (name = "NOM_EMP" ) private String nomEmp; // bi-directional many-to-one association to TbCasillero @ManyToOne @JoinColumn (name = "COD_CAS" ) private TbCasillero tbCasillero; // bi-directional many-to-one association to TbCargo @ManyToOne @JoinColumn (name = "COD_CAR" ) private TbCargo tbCargo; public TbEmpleado() { tbCargo = new TbCargo(); tbCasillero = new TbCasillero(); } public Integer getCodEmp() { return this .codEmp; } public void setCodEmp(Integer codEmp) { this .codEmp = codEmp; } public String getApeEmp() { return this .apeEmp; } public void setApeEmp(String apeEmp) { this .apeEmp = apeEmp; } public String getAreEmp() { return this .areEmp; } public void setAreEmp(String areEmp) { this .areEmp = areEmp; } public int getEdaEmp() { return this .edaEmp; } public void setEdaEmp( int edaEmp) { this .edaEmp = edaEmp; } public Date getFecIngEmp() { return this .fecIngEmp; } public void setFecIngEmp(Date fecIngEmp) { this .fecIngEmp = fecIngEmp; } public String getNomEmp() { return this .nomEmp; } public void setNomEmp(String nomEmp) { this .nomEmp = nomEmp; } public TbCasillero getTbCasillero() { return this .tbCasillero; } public void setTbCasillero(TbCasillero tbCasillero) { this .tbCasillero = tbCasillero; } public TbCargo getTbCargo() { return this .tbCargo; } public void setTbCargo(TbCargo tbCargo) { this .tbCargo = tbCargo; } @Transient private String nombreCompleto; public String getNombreCompleto() { nombreCompleto = getNomEmp().concat( " " ).concat(getApeEmp()); return nombreCompleto; } public void setNombreCompleto(String nombreCompleto) { this .nombreCompleto = nombreCompleto; } // Sobreescribir el método toString para realizar pruebas unitarias @Override public String toString() { return "Empleado [id=" + codEmp + ", apellido=" + apeEmp + ", nombre=" + nomEmp + ", edad=" + edaEmp + ", area=" + areEmp + ", Fecha de ingreso=" + fecIngEmp + ", Cargo=" + tbCargo.getDesCar() + ", casillero=" + tbCasillero.getDesCas() + ", nombreCompleto=" + getNombreCompleto() + "]" ; } } |
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 | package persistence.entity; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the tb_secuencia database table. * */ @Entity @Table (name= "tb_secuencia" ) public class TbSecuencia implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue (strategy=GenerationType.IDENTITY) private String descripcion; private int valor; public TbSecuencia() { } public String getDescripcion() { return this .descripcion; } public void setDescripcion(String descripcion) { this .descripcion = descripcion; } public int getValor() { return this .valor; } public void setValor( int valor) { this .valor = valor; } } |
. TbUsuario
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 | package persistence.entity; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the tb_usuario database table. * */ @Entity @Table (name = "tb_usuario" ) public class TbUsuario implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue (strategy = GenerationType.IDENTITY) @Column (name = "COD_USU" ) private int codUsu; @Column (name = "CON_USU" ) private String conUsu; @Column (name = "NOM_USU" ) private String nomUsu; public TbUsuario() { } public int getCodUsu() { return this .codUsu; } public void setCodUsu( int codUsu) { this .codUsu = codUsu; } public String getConUsu() { return this .conUsu; } public void setConUsu(String conUsu) { this .conUsu = conUsu; } public String getNomUsu() { return this .nomUsu; } public void setNomUsu(String nomUsu) { this .nomUsu = nomUsu; } } |
Paso 8 - Sincronizar la lista de clases y establecer la conexión a la base de datos MySql en el archivo persistence.xml.
Paso 9 - Crear el Entity Listener TbEmpleadoListener.java para comprender el Ciclo de Vida de una entidad en el paquete persistence.entity.listener.
. TbEmpleadoListener.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 | package persistence.entity.listener; import javax.persistence.PostLoad; import javax.persistence.PostPersist; import javax.persistence.PostRemove; import javax.persistence.PostUpdate; import javax.persistence.PrePersist; import javax.persistence.PreRemove; import javax.persistence.PreUpdate; import org.apache.log4j.Logger; import persistence.entity.TbEmpleado; public class TbEmpleadoListener { static Logger logger = Logger.getLogger(TbEmpleado. class .getName()); @PrePersist public void listener_before_insert(TbEmpleado empleado){ logger.debug( "@PrePersist: " +empleado.toString()); } @PreUpdate public void listener_before_update(TbEmpleado empleado){ logger.debug( "@PreUpdate: " +empleado.toString()); } @PreRemove public void listener_before_delete(TbEmpleado empleado){ logger.debug( "@PreRemove: " +empleado.toString()); } @PostLoad public void listener_after_query(TbEmpleado empleado){ logger.debug( "@PostLoad: " +empleado.toString()); } @PostPersist public void listener_after_insert(TbEmpleado empleado){ logger.debug( "@PostPersist: " +empleado.toString()); } @PostUpdate public void listener_after_update(TbEmpleado empleado){ logger.debug( "@PostUpdate: " +empleado.toString()); } @PostRemove public void listener_after_delete(TbEmpleado empleado){ logger.debug( "@PostRemove: " +empleado.toString()); } } |
Paso 10 - Crear el Phase Listener PhaseListener.java para monitorear la ejecución de faces del JSF en el paquete
jsf.listener.
. JSFListener.java
. JSFListener.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 | package jsf.listener; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import org.apache.log4j.Logger; public class JSFListener implements PhaseListener { private static final long serialVersionUID = 1L; static Logger logger = Logger.getLogger(JSFListener. class .getName()); @Override public void beforePhase(PhaseEvent arg0) { logger.info( "Antes de fase: " + arg0.getPhaseId()); } @Override public void afterPhase(PhaseEvent arg0) { logger.info( "Despues de fase: " + arg0.getPhaseId()); } @Override public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; } } |
Paso 11 - Crear la clase
ApplicationBusinessDelegate.java en el paquete business.delegate.
. ApplicationBusinessDelegate.java
. ApplicationBusinessDelegate.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 | package business.delegate; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import business.service.CargoService; import business.service.CargoServiceImpl; import business.service.EmpleadoService; import business.service.EmpleadoServiceImpl; import business.service.LoginService; import business.service.LoginServiceImpl; public class ApplicationBusinessDelegate { private static EntityManagerFactory emf = Persistence.createEntityManagerFactory( "Aplicacion_19a_final_JSF_07" ); public LoginService getLoginService(){ return new LoginServiceImpl(emf); } public EmpleadoService getEmpleadoService(){ return new EmpleadoServiceImpl(emf); } public CargoService getCargoService(){ return new CargoServiceImpl(emf); } } |
Paso 12 - Crear las interfaces LoginService.java, EmpleadoService.java, CargoService.java
y
su clases que la implementan en el paquete business.service.
. LoginService.java
1 2 3 4 5 6 7 8 9 | package business.service; import persistence.entity.TbUsuario; public interface LoginService { public boolean validar(TbUsuario usuario) throws Exception; } |
. EmpleadoService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package business.service; import java.util.List; import persistence.entity.TbEmpleado; public interface EmpleadoService { public List<tbempleado> listarEmpleados() throws Exception; public void registrarEmpleado(TbEmpleado empleado) throws Exception; public TbEmpleado obtenerEmpleado(TbEmpleado empleado) throws Exception; public void modificarEmpleado(TbEmpleado empleado) throws Exception; public void eliminarEmpleado(TbEmpleado empleado) throws Exception; } |
. CargoService.java
1 2 3 4 5 6 7 8 9 10 11 | package business.service; import java.util.List; import persistence.entity.TbCargo; public interface CargoService { public List<tbcargo> listarCargos() throws Exception; } |
. LoginServiceImpl.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 | package business.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import persistence.entity.TbUsuario; import persistence.jpa.TbUsuarioJPA; public class LoginServiceImpl implements LoginService { TbUsuarioJPA usuarioJPA = new TbUsuarioJPA(); private EntityManager em; public LoginServiceImpl(EntityManagerFactory emf) { em = emf.createEntityManager(); } @Override public boolean validar(TbUsuario usuario) throws Exception { int resultado = usuarioJPA.validar(em,usuario); if (resultado == 0 ){ return false ; } else { return true ; } } } |
. EmpleadoServiceImpl.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 | package business.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import persistence.entity.TbEmpleado; import persistence.jpa.TbEmpleadoJPA; public class EmpleadoServiceImpl implements EmpleadoService { static Logger logger = Logger.getLogger(EmpleadoServiceImpl. class .getName()); TbEmpleadoJPA empleadoJPA = new TbEmpleadoJPA(); private EntityManager em; public EmpleadoServiceImpl(EntityManagerFactory emf) { em = emf.createEntityManager(); } @Override public List<tbempleado> listarEmpleados() throws Exception { List<tbempleado> lista = empleadoJPA.listarEmpleados(em); return lista; } @Override public void registrarEmpleado(TbEmpleado empleado) throws Exception { logger.debug( "Registrando un nuevo empleado" ); empleadoJPA.registrarEmpleado(em,empleado); mostrar(empleadoJPA.listarEmpleados(em)); } @Override public TbEmpleado obtenerEmpleado(TbEmpleado empleado) throws Exception { TbEmpleado entidad = empleadoJPA.obtenerEmpleado(em,empleado); return entidad; } @Override public void modificarEmpleado(TbEmpleado empleado) throws Exception { logger.debug( "Actualizamos un empleado" ); empleadoJPA.modificarEmpleado(em,empleado); mostrar(empleadoJPA.listarEmpleados(em)); } @Override public void eliminarEmpleado(TbEmpleado empleado) throws Exception { logger.debug( "Eliminamos un empleado" ); empleadoJPA.eliminarEmpleado(em,empleado); mostrar(empleadoJPA.listarEmpleados(em)); } private static void mostrar(List<tbempleado> listaEntidad){ for ( int i = 0 ; i < listaEntidad.size(); i++) { TbEmpleado entidad = (TbEmpleado) listaEntidad.get(i); logger.info(entidad.toString()); } } } |
. CargoServiceImpl.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 | package business.service; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import persistence.entity.TbCargo; import persistence.jpa.TbCargoJPA; public class CargoServiceImpl implements CargoService { TbCargoJPA cargo = new TbCargoJPA(); private EntityManager em; public CargoServiceImpl(EntityManagerFactory emf) { em = emf.createEntityManager(); } @Override public List<tbcargo> listarCargos() throws Exception { List<tbcargo> lista = cargo.listarCargos(em); return lista; } } |
Paso 13 - Crear el paquete
persistence.jpa que contendrá las clases donde se implementará las
funcionalidades de acceso a base de datos y operaciones CRUD con las tablas
relacionales TbCargoJPA.java, TbEmpleadoJPA.java, TbUsuarioJPA.java.
. TbCargoJPA.java
. TbCargoJPA.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package persistence.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import persistence.entity.TbCargo; public class TbCargoJPA { public List listarCargos(EntityManager em) { String query = "select c from TbCargo c order by c.codCar" ; Query emquery = em.createQuery(query); List lista = emquery.getResultList(); return lista; } } |
.
TbEmpleadoJPA.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 | package persistence.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import persistence.entity.TbEmpleado; public class TbEmpleadoJPA { public List listarEmpleados(EntityManager em) { String query = "select e from TbEmpleado e order by e.codEmp" ; Query emquery = em.createQuery(query); List lista = emquery.getResultList(); return lista; } public void registrarEmpleado(EntityManager em, TbEmpleado empleado) { em.getTransaction().begin(); em.persist(empleado); em.flush(); em.getTransaction().commit(); } public TbEmpleado obtenerEmpleado(EntityManager em, TbEmpleado empleado) { TbEmpleado entidad = (TbEmpleado)em.find(TbEmpleado. class , empleado.getCodEmp()); em.detach(entidad); return entidad; } public void modificarEmpleado(EntityManager em, TbEmpleado empleado) { em.getTransaction().begin(); em.merge(empleado); em.flush(); em.getTransaction().commit(); } public void eliminarEmpleado(EntityManager em, TbEmpleado empleado) { em.getTransaction().begin(); TbEmpleado entidad = (TbEmpleado)em.find(TbEmpleado. class , empleado.getCodEmp()); em.remove(entidad); em.flush(); em.getTransaction().commit(); } } |
.
TbUsuarioJPA.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package persistence.jpa; import javax.persistence.EntityManager; import javax.persistence.Query; import persistence.entity.TbUsuario; public class TbUsuarioJPA { public int validar(EntityManager em, TbUsuario usuario) { String query = "select count(u) from TbUsuario u where u.nomUsu=:username and u.conUsu=:password " ; Query emquery = em.createQuery(query); emquery.setParameter( "username" , usuario.getNomUsu()); emquery.setParameter( "password" , usuario.getConUsu()); Long c = (Long)emquery.getSingleResult(); return c.intValue(); } } |
Paso
14 - Crear
los managed bean EmpleadoBean.java, ListadosBean.java, localeBean.java,
LoginBean.java dentro del paquete jsf.managed.
.
EmpleadoBean.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 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 | package jsf.managed; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import persistence.entity.TbCargo; import persistence.entity.TbEmpleado; import business.delegate.ApplicationBusinessDelegate; import business.service.CargoService; import business.service.EmpleadoService; @ManagedBean (name= "empleado" ) @SessionScoped public class EmpleadoBean { // Business Layer public static ApplicationBusinessDelegate abd = new ApplicationBusinessDelegate(); public static EmpleadoService empleadoService; public static CargoService cargoService; public List<tbempleado>empleadoList; public List<tbcargo> cargoList; public TbEmpleado empleado = new TbEmpleado(); public TbCargo cargo = new TbCargo(); public List<tbempleado> getEmpleadoList() { return empleadoList; } public void setEmpleadoList(List<tbempleado> empleadoList) { this .empleadoList = empleadoList; } public List<tbcargo> getCargoList() { return cargoList; } public void setCargoList(List<tbcargo> cargoList) { this .cargoList = cargoList; } public TbEmpleado getEmpleado() { return empleado; } public void setEmpleado(TbEmpleado empleado) { this .empleado = empleado; } public TbCargo getCargo() { return cargo; } public void setCargo(TbCargo cargo) { this .cargo = cargo; } public String listarEmpleados() throws Exception{ System.out.println( "Estoy en el método listarEmpleados() - INI" ); empleadoService = abd.getEmpleadoService(); empleadoList = empleadoService.listarEmpleados(); System.out.println( "Estoy en el método listarEmpleados() - FIN" ); return "empleadoListado" ; } public String inicializar() throws Exception{ System.out.println( "Estoy en el método inicializar() - INI" ); String codigo=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get( "codigo" ); // HttpServletRequest mirequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest(); // String codigo2=(String) mirequest.getParameter("codigo") ; // FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().put("cargarrequest", "Pronado"); // mirequest.setAttribute("mi_clave_de_request", "cargar atributo"); if (codigo!= null && codigo.length()> 0 ){ empleadoService = abd.getEmpleadoService(); empleado.setCodEmp(Integer.parseInt(codigo)); empleado=empleadoService.obtenerEmpleado(empleado); } else { empleado= new TbEmpleado(); } System.out.println( "Estoy en el método inicializar() - FIN" ); return "empleadoEdicion" ; } public String insertarOActualizar() throws Exception{ System.out.println( "Estoy dentro del método insertarOActualizar() - INI" ); empleadoService = abd.getEmpleadoService(); if (empleado!= null ){ empleadoService.modificarEmpleado(empleado); } else { empleadoService.registrarEmpleado(empleado); } System.out.println( "Estoy dentro del método insertarOActualizar() - FIN" ); return listarEmpleados(); } public String eliminarEmpleado() throws Exception{ System.out.println( "Estoy dentro del método eliminarEmpleado() - INI" ); String codigo = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get( "codigo" ); empleadoService = abd.getEmpleadoService(); empleado.setCodEmp(Integer.parseInt(codigo)); empleadoService.eliminarEmpleado(empleado); System.out.println( "Estoy dentro del método eliminarEmpleado() - FIN" ); return listarEmpleados(); } public String verDetalle() throws Exception{ System.out.println( "Estoy dentro del método verDetalle() - INI" ); String codigo = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get( "codigo" ); empleadoService = abd.getEmpleadoService(); empleado.setCodEmp(Integer.parseInt(codigo)); empleado = empleadoService.obtenerEmpleado(empleado); System.out.println( "Estoy dentro del método verDetalle() - FIN" ); return "empleadoDetalle" ; } } |
.
ListadosBean.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 | package jsf.managed; import java.util.*; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.faces.model.SelectItem; import business.delegate.ApplicationBusinessDelegate; import business.service.CargoService; import persistence.entity.TbCargo; @ManagedBean (name= "listados" , eager= true ) @ApplicationScoped public class ListadosBean { // Business Layer private static ApplicationBusinessDelegate abd = new ApplicationBusinessDelegate(); private static CargoService carService=abd.getCargoService(); private List<selectitem> cargos; public List<selectitem> getCargos() { return cargos; } public void setCargos(List<selectitem> cargos) { this .cargos = cargos; } public ListadosBean(){ System.out.println( "Estoy dentro del método ListadosBean() - INI" ); cargos= new ArrayList<selectitem>(); try { Iterator<tbcargo> iterator= carService.listarCargos().iterator(); while (iterator.hasNext()){ TbCargo cargo=iterator.next(); cargos.add( new SelectItem(cargo.getCodCar(), cargo.getDesCar())); } } catch (Exception e) { e.printStackTrace(); } System.out.println( "Estoy dentro del método ListadosBean() - FIN" ); } } |
. LocaleBean.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 | package jsf.managed; import java.util.Locale; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; @ManagedBean (name= "idioma" ) @SessionScoped public class LocaleBean { private Locale locale=FacesContext.getCurrentInstance().getViewRoot().getLocale(); private String idioma; public Locale getLocale() { return locale; } public String getIdioma() { return idioma; } public void setIdioma(String idioma) { locale= new Locale(idioma); this .idioma=idioma; } } |
.
LoginBean.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 | package jsf.managed; import java.util.ResourceBundle; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import persistence.entity.TbUsuario; import business.delegate.ApplicationBusinessDelegate; import business.service.LoginService; @ManagedBean (name= "login" ) @SessionScoped public class LoginBean { // Business Layer public static ApplicationBusinessDelegate abd = new ApplicationBusinessDelegate(); public static LoginService loginService; private TbUsuario usuario = new TbUsuario(); public TbUsuario getUsuario() { return usuario; } public void setUsuario(TbUsuario usuario) { this .usuario = usuario; } public String validar() throws Exception{ loginService = abd.getLoginService(); if (loginService.validar(usuario)){ return "paginas/principal" ; } else { ResourceBundle resourceBundle = ResourceBundle.getBundle( "recursos.textos" , FacesContext.getCurrentInstance().getViewRoot().getLocale()); FacesMessage facesMessage = new FacesMessage(resourceBundle.getString( "error_login_ok" )); FacesContext.getCurrentInstance().addMessage( null , facesMessage); return "inicio" ; } } } |
Método consultar:
-em.getResultList(): Obtiene lista de entidades, en base al JPQL definido
Método insertar:
-em.persist(entidadEmpleado): Genera un insert a la tabla relacional mapeada con los datos del objeto.
Método actualizar:
-em.merge(entidadEmpleado): Genera un update a la tabla relacional mapeada con los datos del objeto.
Método eliminar:
-Es necesario primero realizar una búsqueda por llave primaria para asociar el objeto entidad a la transacción con JPA
-em.remove(entidadEmpleado): Genera un delete a la tabla relacional mapeada con los datos del objeto.
-em.find(ClaseEntidad.class, valorLlavePrimaria): Realiza una búsqueda por llave primaria en la tabla que representa la Clase Entidad.
IMPORTANTE:
. Asegúrense que los objetos “entidad” fueron cargados con todos los valores necesarios en sus atributos antes de ejecutar las transacciones, de lo contrario puede dar error al momento de ejecutarlas.
3. Crear los archivos de recursos de texto
Paso 14 - Crear los archivo textos.properties y textos_en.properties dentro del paquete pe.edu.cibertec.recursos
Personalizar mensajes de validación
. textos.properties
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 | #key= value #Titulos titulo_cabecera=Desarrollo de Aplicaciones Web II titulo_contenido=Bienvenido titulo_pie=APRENDER COMO JUGANDO titulo_principal=Bienvenido a la zona de Administracion titulo_empleados=> Ver Empleados < titulo_empleado_edit=> Editar Empleado < titulo_empleado_add=> Agregar Empleado < titulo_empleado_detail=> Detalle Empleado < titulo_formulario_simple=FORMULARIO SIMPLE titulo_formulario_prime=FORMULARIO CON PRIME FACES #Sección menu menu_opciones=Opciones menu_item1=Mantenimiento Empleado enlace_inicio=Inicio #Formulario label_usuario=Usuario label_contrasena=Contraseña label_nombre=Nombre label_apellido=Apellido label_edad=Edad label_area=Area label_cargo=Cargo label_casillero=Casillero label_fechaIngreso=Fecha de Ingreso label_codigo=Codigo label_nombre_completo= Nombre Completo label_boton_grabar=Grabar label_boton_limpiar=Limpiar label_boton_retornar=Retornar label_boton_buscar=Buscar label_boton_nuevo=Nuevo label_boton_acceder=Acceder label_boton_actualizar=A label_boton_eliminar=E label_boton_detalle=Ver #mensajes de éxito mensaje_registro_ok=Registro exitoso mensaje_eliminar_ok=Se elimino vendedor con código {0} mensaje_actualizar_ok= Se actualizo vendedor con código {0} mensaje_registro_ok= Se registro empleado #mensajes de errors error_login_ok=Datos no validos errors_general=Ocurrio un error #Validaciones javax.faces.component.UIInput.REQUIRED={0}: Dato Obligatorio javax.faces.validator.RegexValidator.NOT.MATCHED=No cumple formato javax.faces.validator.RegexValidator.NOT.MATCHED.detail=Valor de campo ''{1}'' no cumple formato javax.faces.validator.LengthValidator.MAXIMUM={1}: Longitud de texto mayor a la permitida: ''{0}'' javax.faces.validator.LengthValidator.MINIMUM={1}: Longitud de texto menor a la permitida: ''{0}'' javax.faces.validator.LongRangeValidator.NOT.IN.RANGE={2}: Valor fuera de rango ( {0} - {1} ) |
. textos_en.properties
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 | #key= value #Titulos titulo_cabecera=Application Development Web II titulo_contenido=Welcome titulo_pie=APRENDER COMO JUGANDO titulo_principal=Welcome to the site of administration titulo_empleados=> See Employees < titulo_empleado_edit=> Edit Employee < titulo_empleado_add=> Add Employee< titulo_empleado_detail=> Detail Empleado < titulo_formulario_simple=SIMPLE FORM titulo_formulario_prime=FORM WITH PRIMEFACES #Seccion menu menu_opciones=Options menu_item1=Employee Maintenance enlace_inicio=Home #Formulario label_usuario=Username label_contrasena=Password label_nombre=Name label_apellido=Last Name label_edad=Age label_area=Area label_cargo=Charge label_casillero=Locker label_fechaIngreso=Join Date label_codigo=Code label_nombre_completo= Full Name label_boton_grabar=Record label_boton_limpiar=Clean label_boton_retornar=Retornar label_boton_buscar=Buscar label_boton_nuevo=New label_boton_acceder=Log in label_boton_actualizar=A label_boton_eliminar=E label_boton_detalle=Ver #Mensajes de error error_login_ok=Invalid data errors_general=An error occurred #Mensajes de éxito mensaje_registro_ok=successful registration mensaje_eliminar_ok=Vendor code was eliminated {0} mensaje_actualizar_ok= Vendor code was updated {0} mensaje_registro_ok= Was recorded employee #Validaciones javax.faces.component.UIInput.REQUIRED={0}: Required javax.faces.validator.RegexValidator.NOT_MATCHED= Incorrect Format javax.faces.validator.RegexValidator.NOT_MATCHED_detail=Value of ''{1}'' has incorrect format javax.faces.validator.LengthValidator.MAXIMUM={1}: Maximum length: ''{0}'' javax.faces.validator.LengthValidator.MINIMUM={1}: Minimum length: ''{0}'' javax.faces.validator.LongRangeValidator.NOT_IN_RANGE={2}: Value out of range ( {0} - {1} ) |
4. Crear la plantilla faceles
Paso 15 - Crear la página plantilla.xhtml dentro de la carpeta plantillas y sus secciones cabecera.xhtml, menu.xhtml y pie.xhtml dentro de la carpeta secciones como se muestra en la siguiente imagen:
. plantilla.xhtml
Configurar con FACELETS la plantilla de diseño de página
. Para ello primero debemos referenciar los taglibs
. Luego incluir las secciones requeridas utilizando la etiqueta ui:insert cuyo contenido por defecto se define con la etiqueta ui:include según:
. Cada página referenciada con la etiqueta ui:include debe definir cuál será el contenido que incluirá en la plantilla. Ello se realiza con la etiqueta ui:composition según:
. Se observa que la sección contenido no incluye ninguna página por defecto. Esta sección contendrá el contenido de las diversas páginas del aplicativo que irá cambiando en tiempo de ejecución. Tenemos que sobreescribir en cada página del aplicativo la sección en mención con la etiqueta ui:composition para referenciar la plantilla y la etiqueta ui:define para definir el contenido a incluir en ui:insert= “body”.
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 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < f:view locale = "#{idioma.locale}" > < h:head > < title > < h:outputText value = "DAW II" /> </ title > </ h:head > < h:body > < div id = "page" > < div id = "cabecera" > < ui:insert name = "header" > < ui:include src = "/secciones/cabecera.xhtml" /> </ ui:insert > </ div > < div id = "menu" style = "background-color:silver;" > < ui:insert name = "menu" > < ui:include src = "/secciones/menu.xhtml" /> </ ui:insert > </ div > < div id = "contenido" > < ui:insert name = "body" > </ ui:insert > </ div > < div id = "pie" > < ui:insert name = "footer" > < ui:include src = "/secciones/pie.xhtml" /> </ ui:insert > </ div > </ div > </ h:body > </ f:view > </ html > |
. cabecera.xhtml
1 2 3 4 5 6 7 8 9 10 11 12 | < html xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets" xmlns = "http://www.w3.org/1999/xhtml" > < h:head > </ h:head > < h:body > < ui:composition > < h:panelgrid columns = "2" > < h:graphicimage style = "height: 100px; width: 120px;" url = "/images/logo.png" > < h:outputtext style = "font-size: 2em;" value = "#{texto.titulo_cabecera}" > </ h:outputtext ></ h:graphicimage ></ h:panelgrid > </ ui:composition > </ h:body > </ html > |
. menu.xhtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < h:head > </ h:head > < h:body > < ui:composition > < h:form > < h:panelGrid columns = "1" > < h:commandLink value = "#{texto.menu_item1}" action = "#{empleado.listarEmpleados}" /> </ h:panelGrid > </ h:form > < hr /> </ ui:composition > </ h:body > </ html > |
. pie.xhtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < h:head > </ h:head > < h:body > < ui:composition > < hr /> < h:panelGrid columns = "1" > < h:outputText value = "#{texto.titulo_pie}" /> </ h:panelGrid > </ ui:composition > </ h:body > </ html > |
5. Crear las páginas XHTML
Paso 15 - Crear la página inicio.xhtml dentro del WebContent, principal.xhtml, empleadoListado.xhtml, empleadoEdicion.xhtml y empleadoDetalle.xhtml en la carpeta paginas dentro del webContent.
Tenemos que sobreescribir en cada página del aplicativo la sección body con la etiqueta ui:composition para referenciar la plantilla y la etiqueta ui:define para definir el contenido a incluir en ui:insert= “body”.
Reemplazar textos estáticos en páginas JSF por los definido en el archivo de recursos de texto
Añadir validaciones a campos de formulario y emplear el uso del atributo label
Definir id a cada campo y asociarlo a un elemento h:message
. inicio.xhtml
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 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < h:head > </ h:head > < h:body > < ui:composition template = "/plantillas/externa.xhtml" > < ui:define name = "body" > < h:form > < h:panelGrid columns = "2" > < h:outputText value = "Idioma" /> < h:selectOneMenu value = "#{idioma.idioma}" onchange = "submit()" > < f:selectItem itemValue = "" itemLabel = "Seleccionar" /> < f:selectItem itemValue = "en" itemLabel = "English" /> < f:selectItem itemValue = "es" itemLabel = "Español" /> </ h:selectOneMenu > </ h:panelGrid > </ h:form > < h1 >Logueo con JSF</ h1 > < h:form > < h:panelGrid columns = "2" > < f:facet name = "header" >#{texto.titulo_formulario_simple}</ f:facet > < h:outputLabel value = "#{texto.label_usuario}" /> < h:inputText id = "id" value = "#{login.usuario.nomUsu}" /> < h:outputLabel value = "#{texto.label_contrasena}" /> < h:inputSecret value = "#{login.usuario.conUsu}" /> < f:facet name = "footer" > < h:messages /> < h:commandButton value = "#{texto.label_boton_acceder}" action = "#{login.validar}" /> </ f:facet > </ h:panelGrid > </ h:form > < h1 >Logueo con PrimeFaces</ h1 > < h:form > < h:panelGrid columns = "2" > < f:facet name = "header" >#{texto.titulo_formulario_prime}</ f:facet > < h:outputLabel value = "#{texto.label_usuario}" /> < p:inputText value = "#{login.usuario.nomUsu}" required = "true" label = "#{texto.label_usuario}" /> < h:outputLabel value = "#{texto.label_contrasena}" /> < p:password value = "#{login.usuario.conUsu}" required = "true" feedback = "true" promptLabel = "" label = "#{texto.label_contrasena}" /> < f:facet name = "footer" > < p:messages id = "mensajePrime" /> < p:commandButton value = "#{texto.label_boton_acceder}" action = "#{login.validar}" update = "mensajePrime" ajax = "true" /> </ f:facet > </ h:panelGrid > </ h:form > </ ui:define > </ ui:composition > </ h:body > </ html > |
. empleadoListado.xhtml
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 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < h:head > </ h:head > < h:body > < ui:composition template = "/plantillas/plantilla.xhtml" > < ui:define name = "body" > < p:panelGrid columns = "1" id = "panel" styleClass = "ui-panelgrid" > < h:outputText value = "#{texto.titulo_empleados}" /> < h:form prependId = "false" > < p:commandButton value = "#{texto.label_boton_buscar}" action = "#{empleado.listarEmpleados}" update = "empleados" /> < p:commandButton value = "#{texto.label_boton_nuevo}" action = "#{empleado.inicializar}" ajax = "false" /> < p:separator /> < p:dataTable id = "empleados" value = "#{empleado.empleadoList}" var = "emp" rowKey = "#{emp.codEmp}" > < f:facet name = "header" >Principales Datos</ f:facet > < p:column headerText = "#{texto.label_codigo}" >#{emp.codEmp}</ p:column > < p:column headerText = "#{texto.label_nombre_completo}" >#{emp.nombreCompleto}</ p:column > < p:column > < h:commandLink action = "#{empleado.inicializar}" value = "#{texto.label_boton_actualizar}" > < f:param name = "codigo" value = "#{emp.codEmp}" /> </ h:commandLink > </ p:column > < p:column > < h:commandLink action = "#{empleado.eliminarEmpleado}" value = "#{texto.label_boton_eliminar}" > < f:param name = "codigo" value = "#{emp.codEmp}" /> </ h:commandLink > </ p:column > < p:column > < h:commandLink action = "#{empleado.verDetalle}" value = "#{texto.label_boton_detalle}" > < f:param name = "codigo" value = "#{emp.codEmp}" /> </ h:commandLink > </ p:column > </ p:dataTable > </ h:form > </ p:panelGrid > </ ui:define > </ ui:composition > </ h:body > </ html > |
. empleadoEdicion.xhtml
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 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < h:head > </ h:head > < h:body > < ui:composition template = "/plantillas/plantilla.xhtml" > < ui:define name = "body" > < h:form id = "formEmpleado" > < p:panelGrid columns = "3" id = "panel" > < f:facet name = "header" >#{texto.titulo_empleado_add}</ f:facet > < p:outputLabel for = "nombre" value = "#{texto.label_nombre}" /> < p:inputText value = "#{empleado.empleado.nomEmp}" required = "true" id = "nombre" label = "#{texto.label_nombre}" > < p:ajax update = "msgNombre" event = "blur" /> </ p:inputText > < p:message id = "msgNombre" for = "nombre" /> < p:outputLabel for = "apellido" value = "#{texto.label_apellido}" /> < p:inputText value = "#{empleado.empleado.apeEmp}" required = "true" id = "apellido" label = "#{texto.label_apellido}" > < p:ajax update = "msgApellido" event = "blur" /> </ p:inputText > < p:message id = "msgApellido" for = "apellido" /> < p:outputLabel for = "edad" value = "#{texto.label_edad}" /> < p:inputText value = "#{empleado.empleado.edaEmp}" required = "true" id = "edad" label = "#{texto.label_edad}" > < p:ajax update = "msgEdad" event = "blur" /> </ p:inputText > < p:message id = "msgEdad" for = "edad" /> < p:outputLabel for = "fecIng" value = "#{texto.label_fechaIngreso}" /> < p:calendar value = "#{empleado.empleado.fecIngEmp}" required = "true" id = "fecIng" effect = "fadeIn" maxdate = "today" pattern = "dd/MM/yyyy" readonlyInput = "true" label = "#{texto.label_fechaIngreso}" ></ p:calendar > < p:message id = "msgFecIng" for = "fecIng" /> < p:outputLabel for = "area" value = "#{texto.label_area}" /> < p:inputText value = "#{empleado.empleado.areEmp}" required = "true" id = "area" label = "#{texto.label_area}" > < p:ajax update = "msgArea" event = "blur" /> </ p:inputText > < p:message id = "msgArea" for = "area" /> < p:outputLabel for = "cargo" value = "#{texto.label_cargo}" /> < p:selectOneMenu value = "#{empleado.empleado.tbCargo.codCar}" id = "cargo" required = "true" > < f:selectItem itemLabel = "Select One" itemValue = "" /> < f:selectItems value = "#{listados.cargos}" /> </ p:selectOneMenu > < p:message id = "msgCargo" for = "cargo" /> < p:outputLabel for = "casillero" value = "#{texto.label_casillero}" /> < p:inputText value = "#{empleado.empleado.tbCasillero.codCas}" required = "true" label = "#{texto.label_casillero}" id = "casillero" > < p:ajax update = "msgCasillero" event = "blur" /> </ p:inputText > < p:message id = "msgCasillero" for = "casillero" /> < f:facet name = "footer" > < p:commandButton value = "#{texto.label_boton_grabar}" action = "#{empleado.insertarOActualizar}" ajax = "false" /> < p:commandButton value = "#{texto.label_boton_retornar}" action = "empleadoListado" immediate = "true" ajax = "false" /> </ f:facet > </ p:panelGrid > </ h:form > </ ui:define > </ ui:composition > </ h:body > </ html > |
. empleadoDetalle.xhtml
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 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" < h:head > </ h:head > < h:body > < ui:composition template = "/plantillas/plantilla.xhtml" > < ui:define name = "body" > < h:form id = "formEmpleado" > < p:panelGrid columns = "2" id = "panel" > < f:facet name = "header" >#{texto.titulo_empleado_detail}</ f:facet > < p:outputLabel value = "#{texto.label_nombre}" /> < h:outputText value = "#{empleado.empleado.nomEmp}" /> < p:outputLabel value = "#{texto.label_apellido}" /> < h:outputText value = "#{empleado.empleado.apeEmp}" /> < p:outputLabel value = "#{texto.label_edad}" /> < h:outputText value = "#{empleado.empleado.edaEmp}" /> < p:outputLabel value = "#{texto.label_fechaIngreso}" /> < p:calendar value = "#{empleado.empleado.fecIngEmp}" pattern = "dd/MM/yyyy" disabled = "true" ></ p:calendar > < p:outputLabel value = "#{texto.label_area}" /> < h:outputText value = "#{empleado.empleado.areEmp}" /> < p:outputLabel value = "#{texto.label_cargo}" /> < p:selectOneMenu value = "#{empleado.empleado.tbCargo.codCar}" disabled = "true" > < f:selectItems value = "#{listados.cargos}" /> </ p:selectOneMenu > < p:outputLabel value = "#{texto.label_casillero}" /> < h:outputText value = "#{empleado.empleado.tbCasillero.desCas}" /> < f:facet name = "footer" > < p:commandButton value = "#{texto.label_boton_retornar}" action = "empleadoListado" immediate = "true" ajax = "false" /> </ f:facet > </ p:panelGrid > </ h:form > </ ui:define > </ ui:composition > </ h:body > </ html > |
Paso 16 - Probar aplicación
ESTRUCTURA FINAL DEL PROYECTO
No hay comentarios, ¡cuéntame algo!
Me gustaría saber tu opinión. ¡Saludos!