Download java server faces
Document related concepts
no text concepts found
Transcript
JAVA SERVER FACES ISIS 3710 Java Server Faces La especificación de JSF incluye: API - Librería de tags - Definición y manejo de estado de componentes Manipulación de eventos en la vista Validación del lado del servidor Conversión de datos Navegación Internacionalización Componentes visuales Binding de componentes a métodos del lado del servidor Java Server Faces Componentes esenciales en el modelo de programación: Managed (backing) beans - Componentes - - Objetos ligeros (POJOs) que pueden operar como controlador, o modelo, o vista-modelo Funciones y atributos que son asociados a componentes visuales vía action and data binding, y listeners Tags predefinidos para componentes visuales y batería de atributos que encapsulan comportamientos visuales, y acciones del lado del servidor Formato XHTML Java Server Faces Contenedor web Browser HTTPRequest archivo.xhtml HTTPResponse (HTML) view Java Server Faces Contenedor web Browser HTTPRequest archivo.xhtml HTTPResponse (HTML) Arbol de componentes del lado del servidor view Java Server Faces Contenedor web Browser HTTPRequest Referencia backing beans, objetos, validadores, y convertidores archivo.xhtml HTTPResponse (HTML) view JSF <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:head> <title>Facelets Hello Greeting</title> </h:head> <h:body> <h:form> <h:inputText id="username" title="My name is: " value="#{hello.name}" required="true" requiredMessage="Error: A name is required." maxlength="25" /> <p></p> <h:commandButton id="submit" value="Submit" action="response"> </h:commandButton> <h:commandButton id="reset" value="Reset" type="reset"> </h:commandButton> </h:form> ... </h:body> </html> Managed beans Objetos ligeros del lado del servidor que son administrados en diferentes alcances @RequestScoped @SessionScoped @ApplicationScoped @ViewScoped @NoneScoped Request Sesión Aplicación Postback a la misma vista EL Managed beans package javaeetutorial.hello1; import javax.enterprise.context.RequestScoped; import javax.inject.Named; @Named @RequestScoped public class Hello { private String name; public Hello() { } public String getName() { return name; } public void setName(String user_name) { this.name = user_name; } } Componentes Los componentes se “importan” usando namespaces de JSF: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h=“http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> : </html> Componentes Los componentes se agregan a una página usando tags predefinidos <f:view> <h:form id=“form1”> <h:outputText id=“lbl_name” value=“Name”> <h:inputText id=“txt_name” value=“NameValue”> </h:form> </f:view> Componentes Los componentes se agregan a una página usando tags predefinidos <f:view> <h:form id=“form1”> <h:outputText id=“lbl_name” value=“Name”> <h:inputText id=“txt_name” value=“NameValue”> </h:form> </f:view> Componentes Los componentes se agregan a una página usando tags predefinidos <f:view> <h:form id=“form1”> <h:outputText id=“lbl_name” value=“Name”> <h:inputText id=“txt_name” value=“NameValue”> </h:form> </f:view> Componentes Los componentes se agregan a una página usando tags predefinidos <f:view> <h:form id=“form1”> <h:outputText id=“lbl_name” value=“Name”> <h:inputText id=“txt_name” value=“NameValue”> </h:form> </f:view> Componentes Los componentes se agregan a una página usando tags predefinidos <f:view> <h:form id=“form1”> <h:outputText id=“lbl_name” value=“Name”> <h:inputText id=“txt_name” value=“NameValue”> </h:form> </f:view> Atributos de los componentes accesskey onchange required actionListener onclick message autocomplete ondbclick size converter onfocus style disabled onkeydown styleclass id onkeypress tabindex immediate onkeyup validator maxlength onmouseover required readonly rendered onblur Bindings Value binding: “bind” de propiedades en managed beans a componentes <h:inputText value=“#{person.name}” /> Action binding: “bind” de un método en managed beans a una acción de un componente. <h:commandButton action=“{personSavePage.savePerson}” /> Listeners Se invocan por medio del atributo actionListener, y no deben tener retorno (contrario a los action/method binding) <h:commandLink id="book" action="bookstore" actionListener="#{actionBean.chooseBookFromLink}"> public void chooseBookFromLink(ActionEvent event) { String current = event.getComponent().getId(); FacesContext context = FacesContext.getCurrentInstance(); String bookId = books.get(current); context.getExternalContext().getSessionMap().put("bookId", bookId); } Ciclo de vida: RestoreView Phase Initial request - La vista de una JSF es agregada al FacesContext Postback - Datos son agregados a una página que es el resultado de un request inicial La vista ya existe en el FacesContext Las nuevos valores que vienen en el request, se usan para actualizar la vista en el servidor - Ciclo de vida: Restore View Phase Contenedor web action Enlace Botón archivo.xhtml FacesContext Ciclo de vida: Restore View Phase Contenedor web action Enlace Botón archivo.xhtml Componentes son enlazados a 1. Validadores 2. Listeners 3. Convertidores view FacesContext Ciclo de vida: Render Response Phase Contenedor web action Enlace Botón archivo.xhtml HTML view FacesContext Ciclo de vida: Restore View Phase nuevo request Contenedor web Enlace Botón archivo.xhtml view FacesContext Ciclo de vida: Apply Request Values Phase nuevo request Contenedor web Enlace Botón archivo.xhtml datos en el request value=“…” view FacesContext Ciclo de vida: Update Model Values Phase nuevo request Contenedor web Enlace Botón archivo.xhtml datos en el request value=“…” view FacesContext Ciclo de vida: Render Response Phase nuevo request Enlace Botón Contenedor web Error de validación, transformación a metodos del bean, o archivo.xhtml error generado en el negocio <h:message/> <h:messages/> view FacesContext Componentes Vista Formulario Label Input Password Text area Input hidden Checkbox Checkbox (group) Imagen Enlace (GET request) Enlace (POST request) Botón <f:view> <h:form> <h:outputText> <h:inputText> <h:inputSecret> <h:inputTextArea> <h:inputHidden> <h:selectBooleanCheckBox <h:selectManyCheckBox> <h:graphicImage> <h:link> <h:commandLink> <h:commandButton> Componentes Enlace (URL) Mensaje Todos los mensajes Tabla HTML Radio List Combo <h:outputLink> <h:message> <h:messages> <h:panelGrid> <h:selectOneRadio> <h:selectOneListbox> <h:selectOneMenu> Convertidor String-> número Convertidor Sting-> Date Validador longitud Validador rango entero Validador rango real <f:convertNumber> <f:convertDateTime> <f:validateLength> <f:validateLongRange> <f:validateDoubleRange> Componentes <?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://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>h:validateLength Example</h2> <h:form> <h:inputText id="nameInput" value="#{userData.name}" label="name" > <f:validateLength minimum="5" maximum="8" /> </h:inputText> <h:commandButton value="submit" action="result"/> <h:message for="nameInput" style="color:red" /> </h:form> </h:body> </html> Componentes <?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://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>h:validateLength Example</h2> <h:form> <h:inputText id="nameInput" value="#{userData.name}" label="name" > <f:validateLength minimum="5" maximum="8" /> </h:inputText> <h:commandButton value="submit" action="result"/> <h:message for="nameInput" style="color:red" /> </h:form> </h:body> </html> Componentes <?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://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>h:validateLength Example</h2> <h:form> <h:inputText id="nameInput" value="#{userData.name}" label="name" > <f:validateLength minimum="5" maximum="8" /> </h:inputText> <h:commandButton value="submit" action="result"/> <h:message for="nameInput" style="color:red" /> </h:form> </h:body> </html> Data Tables <h:dataTable value="#{userData.employees}" var="employee" styleClass="employeeTable" headerClass="employeeTableHeader" rowClasses="employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name="header">Name</f:facet> #{employee.name} </h:column> <h:column> <f:facet name="header">Department</f:facet> #{employee.department} </h:column> <h:column> <f:facet name="header">Age</f:facet> #{employee.age} </h:column> <h:column> <f:facet name="header">Salary</f:facet> #{employee.salary} </h:column> </h:dataTable> Data Tables Collección de Beans (POJOS) <h:dataTable value="#{userData.employees}" var="employee" styleClass="employeeTable" headerClass="employeeTableHeader" rowClasses="employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name="header">Name</f:facet> #{employee.name} </h:column> <h:column> <f:facet name="header">Department</f:facet> #{employee.department} </h:column> <h:column> <f:facet name="header">Age</f:facet> #{employee.age} </h:column> <h:column> <f:facet name="header">Salary</f:facet> #{employee.salary} </h:column> </h:dataTable> Data Tables <h:dataTable value="#{userData.employees}" var="employee" styleClass="employeeTable" headerClass="employeeTableHeader" rowClasses="employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name="header">Name</f:facet> #{employee.name} </h:column> <h:column> <f:facet name="header">Department</f:facet> #{employee.department} </h:column> <h:column> <f:facet name="header">Age</f:facet> #{employee.age} </h:column> <h:column> <f:facet name="header">Salary</f:facet> #{employee.salary} </h:column> </h:dataTable> Data Tables <h:dataTable value="#{userData.employees}" var="employee" styleClass="employeeTable" headerClass="employeeTableHeader" rowClasses="employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name="header">Name</f:facet> #{employee.name} </h:column> <h:column> <f:facet name="header">Department</f:facet> #{employee.department} </h:column> <h:column> <f:facet name="header">Age</f:facet> #{employee.age} </h:column> <h:column> <f:facet name="header">Salary</f:facet> #{employee.salary} </h:column> </h:dataTable> Data Tables <h:dataTable value="#{userData.employees}" var="employee" styleClass="employeeTable" headerClass="employeeTableHeader" rowClasses="employeeTableOddRow,employeeTableEvenRow"> <h:column> <f:facet name="header">Name</f:facet> #{employee.name} </h:column> <h:column> <f:facet name="header">Department</f:facet> #{employee.department} </h:column> <h:column> <f:facet name="header">Age</f:facet> #{employee.age} </h:column> <h:column> <f:facet name="header">Salary</f:facet> #{employee.salary} </h:column> </h:dataTable> Data Tables: HTML generado <table class="employeeTable"> <thead><tr> <th class="employeeTableHeader" <th class="employeeTableHeader" <th class="employeeTableHeader" <th class="employeeTableHeader" </tr></thead> <tbody> <tr class="employeeTableOddRow"> <td>John</td> <td>Marketing</td> <td>30</td> <td>2000.0</td> </tr> <tr class="employeeTableEvenRow"> <td>Robert</td> <td>Marketing</td> <td>35</td> <td>3000.0</td> </tr> </table> scope="col">Name</th> scope="col">Department</th> scope="col">Age</th> scope="col">Salary</th> Modelo de Navegación 1. Vía navegación implícita <h:commandButton id="submit" value="Submit" action="response"> </h:commandButton> 2. Vía reglas de navegación <h:commandButton id="submit" value="Submit" action="success"/> <navigation-rule> <from-view-id>/greeting.xhtml</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/response.xhtml</to-view-id> </navigation-case> </navigation-rule> Modelo de Navegación 3. Vía reglas de navegación y generación dinámica de mapeo en un action method (binding) <h:commandButton id="submit" value="Submit" action="#{cashierBean.submit}" /> <navigation-rule> <from-view-id>/greeting.xhtml</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/response.xhtml</to-view-id> </navigation-case> </navigation-rule> Modelo de Navegación 3. Vía reglas de navegación y generación dinámica de mapeo en un action method (binding) <h:commandButton id="submit" action="#{adminBean.createStudent(studentManager.newStudent)}" value="#{bundle['action.submit']}"/> @Named @RequestScope public class AdminBean{ … public String createStudent(Student student) { em.persist(student); return "createdStudent"; } … } Integración con AJAX <f:ajax execute=“componentes-entrada" render=“componentes-salida” /> <h:inputText value="#{bean.message}"> <f:ajax /> </h:inputText> Integración con AJAX <h:form> <h:inputText id="name" value=“#{userBean.name}”> </h:inputText> <h:outputText id=“output" value="#{userData.welcome}"/> <h:commandButton value="Welcome"> <f:ajax execute="name" render="output" /> </h:commandButton> </h:form> Integración con AJAX <h:form> <h:inputText id="tickets" value=“#{bean.tickets}"> <f:ajax event="change" render="total" listener=“#{reservationBean.calculateTotal}"/> </h:inputText> <h:outputText id="total" value=“#{bean.total}"> </h:outputText> </h:form> Aplicaciones web con Java Generación de contenido desde un servlet Contenedor web Browser HTTPRequest servlet HTTPResponse (HTML, o archivos) Aplicaciones web con Java Generación de contenido asíncrona desde un servlet Contenedor web Browser HTTPRequest/AJAX servlet HTTPResponse (datos) Aplicaciones web con Java Servlet como controlador (MVC sin binding) Contenedor web Browser HTTPRequest servlet HTTPResponse (HTML) JSP Aplicaciones web con Java Websockets (full duplex) Contenedor web Browser HTTPRequest HTML HTML* HTTPRequest Datos Endpoint Aplicaciones web con Java JSF (MVC con bindings, MVVM) Contenedor web Browser HTTPRequest HTML JSF Backing beans, listeners Aplicaciones web con Java JSF + AJAX (MVC con bindings, MVVM) Contenedor web Browser HTTPRequest, AJAX HTML, datos JSF Backing beans, listeners