Sunteți pe pagina 1din 46

CREACION DE UN PROYECTO CON JSF A PARTIR DE UNA BASE DE DATOS.

1.- Levantar la base de datos prueba desde Netbeans:


2.-Crear un pool de conexiones y un dataSource.
Guiarse por la url: http://wiki.netbeans.org/PoolConexionesGlassfishNetBeans
Copiar el archivo mysql-connector-java-5.1.23-bin en la carpeta

\glassfish4\glassfish\domains\domain1\lib
De esta manera se crean el pool: connectionPruebaPool y el dataSource: dsPrueba.
Desde Netbeans:
3.- Crear un proyecto web Netbeans:

3.- Crear un Entity Classes from Database.


4.-Crear JSF Pages from Entity Classes
5.- Hacer un deploy al proyecto.
Si todo sale bien, debe aparecer la pantalla:

6.- Ejecutar el proyecto y visualizar resultados:


CODIGO FUENTE DE VARIAS xhtml:
Index.xhtml:

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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
<h:outputStylesheet name="css/jsfcrud.css"/>
</h:head>
<h:body>
Hello from Facelets
<br />
<h:link outcome="/empleados/List" value="Show All Empleados Items"/>
<br />
<h:link outcome="/lugGeograf/List" value="Show All LugGeograf Items"/>
<br />
<h:link outcome="/personas/List" value="Show All Personas Items"/>
</h:body>
</html>

List.xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">

<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.ListPersonasTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:form styleClass="jsfcrud_list_form">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:outputText escape="false" value="#{bundle.ListPersonasEmpty}"
rendered="#{personasController.items.rowCount == 0}"/>
<h:panelGroup rendered="#{personasController.items.rowCount > 0}">
<h:outputText value="#{personasController.pagination.pageFirstItem +
1}..#{personasController.pagination.pageLastItem +
1}/#{personasController.pagination.itemsCount}"/>&nbsp;
<h:commandLink action="#{personasController.previous}" value="#{bundle.Previous}
#{personasController.pagination.pageSize}"
rendered="#{personasController.pagination.hasPreviousPage}"/>&nbsp;
<h:commandLink action="#{personasController.next}" value="#{bundle.Next}
#{personasController.pagination.pageSize}"
rendered="#{personasController.pagination.hasNextPage}"/>&nbsp;
<h:dataTable value="#{personasController.items}" var="item" border="0"
cellpadding="2" cellspacing="0" rowClasses="jsfcrud_odd_row,jsfcrud_even_row"
rules="all" style="border:solid 1px">
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_cedrucpas}"/>
</f:facet>
<h:outputText value="#{item.cedrucpas}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_apellidos}"/>
</f:facet>
<h:outputText value="#{item.apellidos}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_nombres}"/>
</f:facet>
<h:outputText value="#{item.nombres}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_fechaNacimiento}"/>
</f:facet>
<h:outputText value="#{item.fechaNacimiento}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_direccion}"/>
</f:facet>
<h:outputText value="#{item.direccion}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_telefono}"/>
</f:facet>
<h:outputText value="#{item.telefono}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_correo}"/>
</f:facet>
<h:outputText value="#{item.correo}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_lgeCodigo}"/>
</f:facet>
<h:outputText value="#{item.lgeCodigo}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_genero}"/>
</f:facet>
<h:outputText value="#{item.genero}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="&nbsp;"/>
</f:facet>
<h:commandLink action="#{personasController.prepareView}"
value="#{bundle.ListPersonasViewLink}"/>
<h:outputText value=" "/>
<h:commandLink action="#{personasController.prepareEdit}"
value="#{bundle.ListPersonasEditLink}"/>
<h:outputText value=" "/>
<h:commandLink action="#{personasController.destroy}"
value="#{bundle.ListPersonasDestroyLink}"/>
</h:column>
</h:dataTable>
</h:panelGroup>
<br />
<h:commandLink action="#{personasController.prepareCreate}"
value="#{bundle.ListPersonasCreateLink}"/>
<br />
<br />
<h:link outcome="/index" value="#{bundle.ListPersonasIndexLink}"/>
</h:form>
</ui:define>
</ui:composition>
</html>

Create.xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">

<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.CreatePersonasTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="#{bundle.CreatePersonasLabel_cedrucpas}" for="cedrucpas" />
<h:inputText id="cedrucpas" value="#{personasController.selected.cedrucpas}"
title="#{bundle.CreatePersonasTitle_cedrucpas}" required="true"
requiredMessage="#{bundle.CreatePersonasRequiredMessage_cedrucpas}"/>
<h:outputLabel value="#{bundle.CreatePersonasLabel_apellidos}" for="apellidos" />
<h:inputText id="apellidos" value="#{personasController.selected.apellidos}"
title="#{bundle.CreatePersonasTitle_apellidos}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_nombres}" for="nombres" />
<h:inputText id="nombres" value="#{personasController.selected.nombres}"
title="#{bundle.CreatePersonasTitle_nombres}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_fechaNacimiento}"
for="fechaNacimiento" />
<h:inputText id="fechaNacimiento"
value="#{personasController.selected.fechaNacimiento}"
title="#{bundle.CreatePersonasTitle_fechaNacimiento}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_direccion}" for="direccion" />
<h:inputText id="direccion" value="#{personasController.selected.direccion}"
title="#{bundle.CreatePersonasTitle_direccion}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_telefono}" for="telefono" />
<h:inputText id="telefono" value="#{personasController.selected.telefono}"
title="#{bundle.CreatePersonasTitle_telefono}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_correo}" for="correo" />
<h:inputText id="correo" value="#{personasController.selected.correo}"
title="#{bundle.CreatePersonasTitle_correo}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_lgeCodigo}" for="lgeCodigo" />
<h:inputText id="lgeCodigo" value="#{personasController.selected.lgeCodigo}"
title="#{bundle.CreatePersonasTitle_lgeCodigo}" />
<h:outputLabel value="#{bundle.CreatePersonasLabel_genero}" for="genero" />
<h:inputText id="genero" value="#{personasController.selected.genero}"
title="#{bundle.CreatePersonasTitle_genero}" />
</h:panelGrid>
<br />
<h:commandLink action="#{personasController.create}"
value="#{bundle.CreatePersonasSaveLink}" />
<br />
<br />
<h:commandLink action="#{personasController.prepareList}"
value="#{bundle.CreatePersonasShowAllLink}" immediate="true"/>
<br />
<br />
<h:link outcome="/index" value="#{bundle.CreatePersonasIndexLink}"/>
</h:form>
</ui:define>
</ui:composition>
</html>

Edit.xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">

<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.EditPersonasTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="#{bundle.EditPersonasLabel_cedrucpas}" for="cedrucpas" />
<h:inputText id="cedrucpas" value="#{personasController.selected.cedrucpas}"
title="#{bundle.EditPersonasTitle_cedrucpas}" required="true"
requiredMessage="#{bundle.EditPersonasRequiredMessage_cedrucpas}"/>
<h:outputLabel value="#{bundle.EditPersonasLabel_apellidos}" for="apellidos" />
<h:inputText id="apellidos" value="#{personasController.selected.apellidos}"
title="#{bundle.EditPersonasTitle_apellidos}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_nombres}" for="nombres" />
<h:inputText id="nombres" value="#{personasController.selected.nombres}"
title="#{bundle.EditPersonasTitle_nombres}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_fechaNacimiento}"
for="fechaNacimiento" />
<h:inputText id="fechaNacimiento"
value="#{personasController.selected.fechaNacimiento}"
title="#{bundle.EditPersonasTitle_fechaNacimiento}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_direccion}" for="direccion" />
<h:inputText id="direccion" value="#{personasController.selected.direccion}"
title="#{bundle.EditPersonasTitle_direccion}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_telefono}" for="telefono" />
<h:inputText id="telefono" value="#{personasController.selected.telefono}"
title="#{bundle.EditPersonasTitle_telefono}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_correo}" for="correo" />
<h:inputText id="correo" value="#{personasController.selected.correo}"
title="#{bundle.EditPersonasTitle_correo}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_lgeCodigo}" for="lgeCodigo" />
<h:inputText id="lgeCodigo" value="#{personasController.selected.lgeCodigo}"
title="#{bundle.EditPersonasTitle_lgeCodigo}" />
<h:outputLabel value="#{bundle.EditPersonasLabel_genero}" for="genero" />
<h:inputText id="genero" value="#{personasController.selected.genero}"
title="#{bundle.EditPersonasTitle_genero}" />
</h:panelGrid>
<h:commandLink action="#{personasController.update}"
value="#{bundle.EditPersonasSaveLink}"/>
<br />
<br />
<h:link outcome="View" value="#{bundle.EditPersonasViewLink}"/>
<br />
<h:commandLink action="#{personasController.prepareList}"
value="#{bundle.EditPersonasShowAllLink}" immediate="true"/>
<br />
<br />
<h:link outcome="/index" value="#{bundle.EditPersonasIndexLink}" />
</h:form>
</ui:define>
</ui:composition>

</html>

List.xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">

<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.ListPersonasTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:form styleClass="jsfcrud_list_form">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:outputText escape="false" value="#{bundle.ListPersonasEmpty}"
rendered="#{personasController.items.rowCount == 0}"/>
<h:panelGroup rendered="#{personasController.items.rowCount > 0}">
<h:outputText value="#{personasController.pagination.pageFirstItem +
1}..#{personasController.pagination.pageLastItem +
1}/#{personasController.pagination.itemsCount}"/>&nbsp;
<h:commandLink action="#{personasController.previous}" value="#{bundle.Previous}
#{personasController.pagination.pageSize}"
rendered="#{personasController.pagination.hasPreviousPage}"/>&nbsp;
<h:commandLink action="#{personasController.next}" value="#{bundle.Next}
#{personasController.pagination.pageSize}"
rendered="#{personasController.pagination.hasNextPage}"/>&nbsp;
<h:dataTable value="#{personasController.items}" var="item" border="0"
cellpadding="2" cellspacing="0" rowClasses="jsfcrud_odd_row,jsfcrud_even_row"
rules="all" style="border:solid 1px">
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_cedrucpas}"/>
</f:facet>
<h:outputText value="#{item.cedrucpas}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_apellidos}"/>
</f:facet>
<h:outputText value="#{item.apellidos}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_nombres}"/>
</f:facet>
<h:outputText value="#{item.nombres}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_fechaNacimiento}"/>
</f:facet>
<h:outputText value="#{item.fechaNacimiento}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_direccion}"/>
</f:facet>
<h:outputText value="#{item.direccion}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_telefono}"/>
</f:facet>
<h:outputText value="#{item.telefono}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_correo}"/>
</f:facet>
<h:outputText value="#{item.correo}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_lgeCodigo}"/>
</f:facet>
<h:outputText value="#{item.lgeCodigo}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListPersonasTitle_genero}"/>
</f:facet>
<h:outputText value="#{item.genero}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="&nbsp;"/>
</f:facet>
<h:commandLink action="#{personasController.prepareView}"
value="#{bundle.ListPersonasViewLink}"/>
<h:outputText value=" "/>
<h:commandLink action="#{personasController.prepareEdit}"
value="#{bundle.ListPersonasEditLink}"/>
<h:outputText value=" "/>
<h:commandLink action="#{personasController.destroy}"
value="#{bundle.ListPersonasDestroyLink}"/>
</h:column>
</h:dataTable>
</h:panelGroup>
<br />
<h:commandLink action="#{personasController.prepareCreate}"
value="#{bundle.ListPersonasCreateLink}"/>
<br />
<br />
<h:link outcome="/index" value="#{bundle.ListPersonasIndexLink}"/>
</h:form>
</ui:define>
</ui:composition>
</html>

View.xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">

<ui:composition template="/template.xhtml">
<ui:define name="title">
<h:outputText value="#{bundle.ViewPersonasTitle}"></h:outputText>
</ui:define>
<ui:define name="body">
<h:panelGroup id="messagePanel" layout="block">
<h:messages errorStyle="color: red" infoStyle="color: green" layout="table"/>
</h:panelGroup>
<h:form>
<h:panelGrid columns="2">
<h:outputText value="#{bundle.ViewPersonasLabel_cedrucpas}"/>
<h:outputText value="#{personasController.selected.cedrucpas}"
title="#{bundle.ViewPersonasTitle_cedrucpas}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_apellidos}"/>
<h:outputText value="#{personasController.selected.apellidos}"
title="#{bundle.ViewPersonasTitle_apellidos}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_nombres}"/>
<h:outputText value="#{personasController.selected.nombres}"
title="#{bundle.ViewPersonasTitle_nombres}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_fechaNacimiento}"/>
<h:outputText value="#{personasController.selected.fechaNacimiento}"
title="#{bundle.ViewPersonasTitle_fechaNacimiento}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_direccion}"/>
<h:outputText value="#{personasController.selected.direccion}"
title="#{bundle.ViewPersonasTitle_direccion}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_telefono}"/>
<h:outputText value="#{personasController.selected.telefono}"
title="#{bundle.ViewPersonasTitle_telefono}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_correo}"/>
<h:outputText value="#{personasController.selected.correo}"
title="#{bundle.ViewPersonasTitle_correo}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_lgeCodigo}"/>
<h:outputText value="#{personasController.selected.lgeCodigo}"
title="#{bundle.ViewPersonasTitle_lgeCodigo}"/>
<h:outputText value="#{bundle.ViewPersonasLabel_genero}"/>
<h:outputText value="#{personasController.selected.genero}"
title="#{bundle.ViewPersonasTitle_genero}"/>
</h:panelGrid>
<br />
<h:commandLink action="#{personasController.destroyAndView}"
value="#{bundle.ViewPersonasDestroyLink}"/>
<br />
<br />
<h:link outcome="Edit" value="#{bundle.ViewPersonasEditLink}"/>
<br />
<h:commandLink action="#{personasController.prepareCreate}"
value="#{bundle.ViewPersonasCreateLink}" />
<br />
<h:commandLink action="#{personasController.prepareList}"
value="#{bundle.ViewPersonasShowAllLink}"/>
<br />
<br />
<h:link outcome="/index" value="#{bundle.ViewPersonasIndexLink}"/>

</h:form>
</ui:define>
</ui:composition>
</html>

PersonaController.java:
package jsf;

import pkprueba.Personas;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import psa.session.PersonasFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@Named("personasController")
@SessionScoped
public class PersonasController implements Serializable {

private Personas current;


private DataModel items = null;
@EJB
private psa.session.PersonasFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;

public PersonasController() {
}

public Personas getSelected() {


if (current == null) {
current = new Personas();
selectedItemIndex = -1;
}
return current;
}

private PersonasFacade getFacade() {


return ejbFacade;
}

public PaginationHelper getPagination() {


if (pagination == null) {
pagination = new PaginationHelper(10) {

@Override
public int getItemsCount() {
return getFacade().count();
}

@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(),
getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}

public String prepareList() {


recreateModel();
return "List";
}

public String prepareView() {


current = (Personas) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}

public String prepareCreate() {


current = new Personas();
selectedItemIndex = -1;
return "Create";
}

public String create() {


try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getStrin
g("PersonasCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured")
);
return null;
}
}

public String prepareEdit() {


current = (Personas) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}

public String update() {


try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getStrin
g("PersonasUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured")
);
return null;
}
}
public String destroy() {
current = (Personas) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}

public String destroyAndView() {


performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}

private void performDestroy() {


try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getStrin
g("PersonasDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured")
);
}
}

private void updateCurrentItem() {


int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex +
1}).get(0);
}
}

public DataModel getItems() {


if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}

private void recreateModel() {


items = null;
}

private void recreatePagination() {


pagination = null;
}

public String next() {


getPagination().nextPage();
recreateModel();
return "List";
}

public String previous() {


getPagination().previousPage();
recreateModel();
return "List";
}

public SelectItem[] getItemsAvailableSelectMany() {


return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}

public SelectItem[] getItemsAvailableSelectOne() {


return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}

public Personas getPersonas(java.lang.String id) {


return ejbFacade.find(id);
}

@FacesConverter(forClass = Personas.class)
public static class PersonasControllerConverter implements Converter {

@Override
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value) {
if (value == null || value.length() == 0) {
return null;
}
PersonasController controller = (PersonasController)
facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "personasController");
return controller.getPersonas(getKey(value));
}

java.lang.String getKey(String value) {


java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}

@Override
public String getAsString(FacesContext facesContext, UIComponent component,
Object object) {
if (object == null) {
return null;
}
if (object instanceof Personas) {
Personas o = (Personas) object;
return getStringKey(o.getCedrucpas());
} else {
throw new IllegalArgumentException("object " + object + " is of type " +
object.getClass().getName() + "; expected type: " + Personas.class.getName());
}
}
}
}

Personas.java:
package pkprueba;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author Fausto
*/
@Entity
@Table(name = "personas")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Personas.findAll", query = "SELECT p FROM Personas p"),
@NamedQuery(name = "Personas.findByCedrucpas", query = "SELECT p FROM
Personas p WHERE p.cedrucpas = :cedrucpas"),
@NamedQuery(name = "Personas.findByApellidos", query = "SELECT p FROM
Personas p WHERE p.apellidos = :apellidos"),
@NamedQuery(name = "Personas.findByNombres", query = "SELECT p FROM
Personas p WHERE p.nombres = :nombres"),
@NamedQuery(name = "Personas.findByFechaNacimiento", query = "SELECT p
FROM Personas p WHERE p.fechaNacimiento = :fechaNacimiento"),
@NamedQuery(name = "Personas.findByDireccion", query = "SELECT p FROM
Personas p WHERE p.direccion = :direccion"),
@NamedQuery(name = "Personas.findByTelefono", query = "SELECT p FROM
Personas p WHERE p.telefono = :telefono"),
@NamedQuery(name = "Personas.findByCorreo", query = "SELECT p FROM
Personas p WHERE p.correo = :correo"),
@NamedQuery(name = "Personas.findByLgeCodigo", query = "SELECT p FROM
Personas p WHERE p.lgeCodigo = :lgeCodigo"),
@NamedQuery(name = "Personas.findByGenero", query = "SELECT p FROM
Personas p WHERE p.genero = :genero")})
public class Personas implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 10)
@Column(name = "CEDRUCPAS")
private String cedrucpas;
@Size(max = 40)
@Column(name = "APELLIDOS")
private String apellidos;
@Size(max = 40)
@Column(name = "NOMBRES")
private String nombres;
@Size(max = 20)
@Column(name = "FechaNacimiento")
private String fechaNacimiento;
@Size(max = 100)
@Column(name = "Direccion")
private String direccion;
@Size(max = 11)
@Column(name = "Telefono")
private String telefono;
@Size(max = 100)
@Column(name = "CORREO")
private String correo;
@Size(max = 25)
@Column(name = "LGE_CODIGO")
private String lgeCodigo;
@Size(max = 10)
@Column(name = "Genero")
private String genero;

public Personas() {
}

public Personas(String cedrucpas) {


this.cedrucpas = cedrucpas;
}

public String getCedrucpas() {


return cedrucpas;
}

public void setCedrucpas(String cedrucpas) {


this.cedrucpas = cedrucpas;
}

public String getApellidos() {


return apellidos;
}

public void setApellidos(String apellidos) {


this.apellidos = apellidos;
}

public String getNombres() {


return nombres;
}

public void setNombres(String nombres) {


this.nombres = nombres;
}

public String getFechaNacimiento() {


return fechaNacimiento;
}

public void setFechaNacimiento(String fechaNacimiento) {


this.fechaNacimiento = fechaNacimiento;
}

public String getDireccion() {


return direccion;
}

public void setDireccion(String direccion) {


this.direccion = direccion;
}

public String getTelefono() {


return telefono;
}

public void setTelefono(String telefono) {


this.telefono = telefono;
}

public String getCorreo() {


return correo;
}

public void setCorreo(String correo) {


this.correo = correo;
}

public String getLgeCodigo() {


return lgeCodigo;
}
public void setLgeCodigo(String lgeCodigo) {
this.lgeCodigo = lgeCodigo;
}

public String getGenero() {


return genero;
}

public void setGenero(String genero) {


this.genero = genero;
}

@Override
public int hashCode() {
int hash = 0;
hash += (cedrucpas != null ? cedrucpas.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Personas)) {
return false;
}
Personas other = (Personas) object;
if ((this.cedrucpas == null && other.cedrucpas != null) || (this.cedrucpas != null &&
!this.cedrucpas.equals(other.cedrucpas))) {
return false;
}
return true;
}

@Override
public String toString() {
return "pkprueba.Personas[ cedrucpas=" + cedrucpas + " ]";
}
}

PersonasFacade.java (session).
package psa.session;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import pkprueba.Personas;

/**
*
* @author Fausto
*/
@Stateless
public class PersonasFacade extends AbstractFacade<Personas> {
@PersistenceContext(unitName = "prbPruebaJSFPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}

public PersonasFacade() {
super(Personas.class);
}
}

Bundle.properties:
PersistenceErrorOccured=A persistence error occurred.
Previous=Previous
Next=Next

EmpleadosCreated=Empleados was successfully created.


EmpleadosUpdated=Empleados was successfully updated.
EmpleadosDeleted=Empleados was successfully deleted.
CreateEmpleadosTitle=Create New Empleados
CreateEmpleadosSaveLink=Save
CreateEmpleadosShowAllLink=Show All Empleados Items
CreateEmpleadosIndexLink=Index
CreateEmpleadosLabel_empCodigo=EmpCodigo:
CreateEmpleadosRequiredMessage_empCodigo=The EmpCodigo field is required.
CreateEmpleadosTitle_empCodigo=EmpCodigo
CreateEmpleadosLabel_empCodigoJefe=EmpCodigoJefe:
CreateEmpleadosTitle_empCodigoJefe=EmpCodigoJefe
CreateEmpleadosLabel_cedrucpas=Cedrucpas:
CreateEmpleadosRequiredMessage_cedrucpas=The Cedrucpas field is required.
CreateEmpleadosTitle_cedrucpas=Cedrucpas
CreateEmpleadosLabel_carCodigo=CarCodigo:
CreateEmpleadosTitle_carCodigo=CarCodigo
CreateEmpleadosLabel_fechaIngreso=FechaIngreso:
CreateEmpleadosTitle_fechaIngreso=FechaIngreso
EditEmpleadosTitle=Edit Empleados
EditEmpleadosSaveLink=Save
EditEmpleadosViewLink=View
EditEmpleadosShowAllLink=Show All Empleados Items
EditEmpleadosIndexLink=Index
EditEmpleadosLabel_empCodigo=EmpCodigo:
EditEmpleadosRequiredMessage_empCodigo=The EmpCodigo field is required.
EditEmpleadosTitle_empCodigo=EmpCodigo
EditEmpleadosLabel_empCodigoJefe=EmpCodigoJefe:
EditEmpleadosTitle_empCodigoJefe=EmpCodigoJefe
EditEmpleadosLabel_cedrucpas=Cedrucpas:
EditEmpleadosRequiredMessage_cedrucpas=The Cedrucpas field is required.
EditEmpleadosTitle_cedrucpas=Cedrucpas
EditEmpleadosLabel_carCodigo=CarCodigo:
EditEmpleadosTitle_carCodigo=CarCodigo
EditEmpleadosLabel_fechaIngreso=FechaIngreso:
EditEmpleadosTitle_fechaIngreso=FechaIngreso
ViewEmpleadosTitle=View
ViewEmpleadosDestroyLink=Destroy
ViewEmpleadosEditLink=Edit
ViewEmpleadosCreateLink=Create New Empleados
ViewEmpleadosShowAllLink=Show All Empleados Items
ViewEmpleadosIndexLink=Index
ViewEmpleadosLabel_empCodigo=EmpCodigo:
ViewEmpleadosTitle_empCodigo=EmpCodigo
ViewEmpleadosLabel_empCodigoJefe=EmpCodigoJefe:
ViewEmpleadosTitle_empCodigoJefe=EmpCodigoJefe
ViewEmpleadosLabel_cedrucpas=Cedrucpas:
ViewEmpleadosTitle_cedrucpas=Cedrucpas
ViewEmpleadosLabel_carCodigo=CarCodigo:
ViewEmpleadosTitle_carCodigo=CarCodigo
ViewEmpleadosLabel_fechaIngreso=FechaIngreso:
ViewEmpleadosTitle_fechaIngreso=FechaIngreso
ListEmpleadosTitle=List
ListEmpleadosEmpty=(No Empleados Items Found)
ListEmpleadosDestroyLink=Destroy
ListEmpleadosEditLink=Edit
ListEmpleadosViewLink=View
ListEmpleadosCreateLink=Create New Empleados
ListEmpleadosIndexLink=Index
ListEmpleadosTitle_empCodigo=EmpCodigo
ListEmpleadosTitle_empCodigoJefe=EmpCodigoJefe
ListEmpleadosTitle_cedrucpas=Cedrucpas
ListEmpleadosTitle_carCodigo=CarCodigo
ListEmpleadosTitle_fechaIngreso=FechaIngreso
LugGeografCreated=LugGeograf was successfully created.
LugGeografUpdated=LugGeograf was successfully updated.
LugGeografDeleted=LugGeograf was successfully deleted.
CreateLugGeografTitle=Create New LugGeograf
CreateLugGeografSaveLink=Save
CreateLugGeografShowAllLink=Show All LugGeograf Items
CreateLugGeografIndexLink=Index
CreateLugGeografLabel_lgeCodigo=LgeCodigo:
CreateLugGeografRequiredMessage_lgeCodigo=The LgeCodigo field is required.
CreateLugGeografTitle_lgeCodigo=LgeCodigo
CreateLugGeografLabel_lgeDescripcion=LgeDescripcion:
CreateLugGeografTitle_lgeDescripcion=LgeDescripcion
CreateLugGeografLabel_lgeTipo=LgeTipo:
CreateLugGeografTitle_lgeTipo=LgeTipo
EditLugGeografTitle=Edit LugGeograf
EditLugGeografSaveLink=Save
EditLugGeografViewLink=View
EditLugGeografShowAllLink=Show All LugGeograf Items
EditLugGeografIndexLink=Index
EditLugGeografLabel_lgeCodigo=LgeCodigo:
EditLugGeografRequiredMessage_lgeCodigo=The LgeCodigo field is required.
EditLugGeografTitle_lgeCodigo=LgeCodigo
EditLugGeografLabel_lgeDescripcion=LgeDescripcion:
EditLugGeografTitle_lgeDescripcion=LgeDescripcion
EditLugGeografLabel_lgeTipo=LgeTipo:
EditLugGeografTitle_lgeTipo=LgeTipo
ViewLugGeografTitle=View
ViewLugGeografDestroyLink=Destroy
ViewLugGeografEditLink=Edit
ViewLugGeografCreateLink=Create New LugGeograf
ViewLugGeografShowAllLink=Show All LugGeograf Items
ViewLugGeografIndexLink=Index
ViewLugGeografLabel_lgeCodigo=LgeCodigo:
ViewLugGeografTitle_lgeCodigo=LgeCodigo
ViewLugGeografLabel_lgeDescripcion=LgeDescripcion:
ViewLugGeografTitle_lgeDescripcion=LgeDescripcion
ViewLugGeografLabel_lgeTipo=LgeTipo:
ViewLugGeografTitle_lgeTipo=LgeTipo
ListLugGeografTitle=List
ListLugGeografEmpty=(No LugGeograf Items Found)
ListLugGeografDestroyLink=Destroy
ListLugGeografEditLink=Edit
ListLugGeografViewLink=View
ListLugGeografCreateLink=Create New LugGeograf
ListLugGeografIndexLink=Index
ListLugGeografTitle_lgeCodigo=LgeCodigo
ListLugGeografTitle_lgeDescripcion=LgeDescripcion
ListLugGeografTitle_lgeTipo=LgeTipo
PersonasCreated=Personas was successfully created.
PersonasUpdated=Personas was successfully updated.
PersonasDeleted=Personas was successfully deleted.
CreatePersonasTitle=Create New Personas
CreatePersonasSaveLink=Save
CreatePersonasShowAllLink=Show All Personas Items
CreatePersonasIndexLink=Index
CreatePersonasLabel_cedrucpas=Cedrucpas:
CreatePersonasRequiredMessage_cedrucpas=The Cedrucpas field is required.
CreatePersonasTitle_cedrucpas=Cedrucpas
CreatePersonasLabel_apellidos=Apellidos:
CreatePersonasTitle_apellidos=Apellidos
CreatePersonasLabel_nombres=Nombres:
CreatePersonasTitle_nombres=Nombres
CreatePersonasLabel_fechaNacimiento=FechaNacimiento:
CreatePersonasTitle_fechaNacimiento=FechaNacimiento
CreatePersonasLabel_direccion=Direccion:
CreatePersonasTitle_direccion=Direccion
CreatePersonasLabel_telefono=Telefono:
CreatePersonasTitle_telefono=Telefono
CreatePersonasLabel_correo=Correo:
CreatePersonasTitle_correo=Correo
CreatePersonasLabel_lgeCodigo=LgeCodigo:
CreatePersonasTitle_lgeCodigo=LgeCodigo
CreatePersonasLabel_genero=Genero:
CreatePersonasTitle_genero=Genero
EditPersonasTitle=Edit Personas
EditPersonasSaveLink=Save
EditPersonasViewLink=View
EditPersonasShowAllLink=Show All Personas Items
EditPersonasIndexLink=Index
EditPersonasLabel_cedrucpas=Cedrucpas:
EditPersonasRequiredMessage_cedrucpas=The Cedrucpas field is required.
EditPersonasTitle_cedrucpas=Cedrucpas
EditPersonasLabel_apellidos=Apellidos:
EditPersonasTitle_apellidos=Apellidos
EditPersonasLabel_nombres=Nombres:
EditPersonasTitle_nombres=Nombres
EditPersonasLabel_fechaNacimiento=FechaNacimiento:
EditPersonasTitle_fechaNacimiento=FechaNacimiento
EditPersonasLabel_direccion=Direccion:
EditPersonasTitle_direccion=Direccion
EditPersonasLabel_telefono=Telefono:
EditPersonasTitle_telefono=Telefono
EditPersonasLabel_correo=Correo:
EditPersonasTitle_correo=Correo
EditPersonasLabel_lgeCodigo=LgeCodigo:
EditPersonasTitle_lgeCodigo=LgeCodigo
EditPersonasLabel_genero=Genero:
EditPersonasTitle_genero=Genero
ViewPersonasTitle=View
ViewPersonasDestroyLink=Destroy
ViewPersonasEditLink=Edit
ViewPersonasCreateLink=Create New Personas
ViewPersonasShowAllLink=Show All Personas Items
ViewPersonasIndexLink=Index
ViewPersonasLabel_cedrucpas=Cedrucpas:
ViewPersonasTitle_cedrucpas=Cedrucpas
ViewPersonasLabel_apellidos=Apellidos:
ViewPersonasTitle_apellidos=Apellidos
ViewPersonasLabel_nombres=Nombres:
ViewPersonasTitle_nombres=Nombres
ViewPersonasLabel_fechaNacimiento=FechaNacimiento:
ViewPersonasTitle_fechaNacimiento=FechaNacimiento
ViewPersonasLabel_direccion=Direccion:
ViewPersonasTitle_direccion=Direccion
ViewPersonasLabel_telefono=Telefono:
ViewPersonasTitle_telefono=Telefono
ViewPersonasLabel_correo=Correo:
ViewPersonasTitle_correo=Correo
ViewPersonasLabel_lgeCodigo=LgeCodigo:
ViewPersonasTitle_lgeCodigo=LgeCodigo
ViewPersonasLabel_genero=Genero:
ViewPersonasTitle_genero=Genero
ListPersonasTitle=List
ListPersonasEmpty=(No Personas Items Found)
ListPersonasDestroyLink=Destroy
ListPersonasEditLink=Edit
ListPersonasViewLink=View
ListPersonasCreateLink=Create New Personas
ListPersonasIndexLink=Index
ListPersonasTitle_cedrucpas=Cedrucpas
ListPersonasTitle_apellidos=Apellidos
ListPersonasTitle_nombres=Nombres
ListPersonasTitle_fechaNacimiento=FechaNacimiento
ListPersonasTitle_direccion=Direccion
ListPersonasTitle_telefono=Telefono
ListPersonasTitle_correo=Correo
ListPersonasTitle_lgeCodigo=LgeCodigo
ListPersonasTitle_genero=Genero
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<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>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>

PaginationHelper.java:
package jsf.util;

import javax.faces.model.DataModel;

public abstract class PaginationHelper {

private int pageSize;


private int page;

public PaginationHelper(int pageSize) {


this.pageSize = pageSize;
}

public abstract int getItemsCount();

public abstract DataModel createPageDataModel();

public int getPageFirstItem() {


return page * pageSize;
}

public int getPageLastItem() {


int i = getPageFirstItem() + pageSize - 1;
int count = getItemsCount() - 1;
if (i > count) {
i = count;
}
if (i < 0) {
i = 0;
}
return i;
}

public boolean isHasNextPage() {


return (page + 1) * pageSize + 1 <= getItemsCount();
}

public void nextPage() {


if (isHasNextPage()) {
page++;
}
}

public boolean isHasPreviousPage() {


return page > 0;
}

public void previousPage() {


if (isHasPreviousPage()) {
page--;
}
}

public int getPageSize() {


return pageSize;
}
}

AbstractFacade.java:
package psa.session;

import java.util.List;
import javax.persistence.EntityManager;

/**
*
* @author Fausto
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {


this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

public void create(T entity) {


getEntityManager().persist(entity);
}

public void edit(T entity) {


getEntityManager().merge(entity);
}

public void remove(T entity) {


getEntityManager().remove(getEntityManager().merge(entity));
}

public T find(Object id) {


return getEntityManager().find(entityClass, id);
}

public List<T> findAll() {


javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}

public List<T> findRange(int[] range) {


javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}

public int count() {


javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}

Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="prbPruebaJSFPU" transaction-type="JTA">
<jta-data-source>jdbc/dsPrueba</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>

S-ar putea să vă placă și