Professional Documents
Culture Documents
Clase 8 Tecnologias
Clase 8 Tecnologias
Definición del
3 4
Software 4/sept 11/sept
ITIL
14/ago Principios Métodos
Operación,
Soporte y COBIT DevOps
DevOps Qué es ? Diseño
Mantenimiento •Maven
27/nov
14 ISO Estrategias 6 Modelos 5
Ingeniería de 25/sept
Software 18/sept
Web
30/oct – Taller 3
Dr. Alfonso Miguel Reyes
Validación
12 16/oct
4/dic – Taller 4 13/nov
Tecnologías
• developing
Java EE 6 is supported
• deploying and only by the GlassFish
• managing server v3.x.
http://netbeans.org/kb/trails/java-ee.html
Java EE 6 Platform
• The Java EE platform uses a simplified programming model. XML
deployment descriptors are optional. Instead, a developer can simply
enter the information as an annotation directly into a Java source file,
and the Java EE server will configure the component at deployment and
runtime
• With annotations, you put the specification information in your code
next to the program element affected.
http://download.oracle.com/javaee/6/tutorial/doc/bnaaw.html
Java EE application model
• an architecture for implementing services as
multitier applications that deliver the scalability,
accessibility, and manageability needed by enterprise-
level applications.
• With this structure you can more easily change one of
the tiers without compromising your entire
application.
• Business and presentation logic - to be implemented
by the developer
• Standard system services – to be provided by the Java
EE platform
http://download.oracle.com/javaee/6/tutorial/doc/bnaaw.html
Java Servlets
• Servlets are Java classes that dynamically process requests and
construct responses.
• Server side replacement for CGI
• Extensions to Java enabled web-servers
• Inherently multi-threaded.
• One thread per request.
• Very efficient.
• Platform independent.
How do Servlets work?
• Servlets run inside a Web Container - the component of the web server
that runs and interacts with Servlets
• Servlet is running on the server listening for requests
• When a request comes in, a new thread is generated by the web
container.
Java EE Containers
Java EE containers
• are the interface between a Java component
and the low-level platform-specific functionality
(i.e. transaction and state management,
multithreading, resource pooling, etc.) that
supports the component.
• provide for the separation of business logic from
resource and lifecycle management.
• this allows developers to focus on writing business logic
rather than writing enterprise infrastructure.
The Java EE platform uses "containers" to simplify development.
http://download.oracle.com/javaee/6/tutorial/doc/bnabo.html
http://www.oracle.com/technetwork/java/javaee/javaee-faq-jsp-135209.html#diff
Java EE Containers
When a request comes in:
• a Servlet needs to be instantiated and create a new thread to
handle the request.
• call the Servlet’s doPost()or doGet() method and pass the
HTTP request and HTTP response objects
• get the request and the response to the Servlet
• manage the life, death and resources of the Servlet
* All of the above are the tasks of the web container.
Java EE Containers
Java EE SERVER
Server
Web
server My codes
PHP
HTTP HTML MySQL
interpreter
Client
Operating System
Web
TCP/IP
browser
Operating
System
Internet
Historically (Java Web App)
Server: response
• Webserver supports HTTP.
Server
<html>
<head>
GET... GET...
</head>
<body>
...
Web
Container Servlet
Application (Java code)
HTTP <html> (Java code)
Client <head>
</head>
<body>
...
<body> Operating System
</html>
Web
TCP/IP
browser
Operating
System
It’s the Container that gives
the Servlet the HTTP request
and response, and it’s the
Internet Container that calls the Servlet’s
methods (e.g. doPost() or doGet())
Historically (Java Web App)
Server: response
• Webserver supports HTTP.
Server
<html>
<head>
GET... GET...
</head>
<body>
...
Servlet
HTTP (Java code)
<html>
Client <head>
</head>
<body>
...
<body> Operating System
</html>
Web
TCP/IP
browser
Operating
System
It’s the Container that gives
the Servlet the HTTP request
and response, and it’s the
Internet Container that calls the Servlet’s
methods (e.g. doPost() or doGet())
(Java Web App) Server: response
• Webserver supports HTTP.
Server
GET...
Grizzly is now the Web server + <html>
<head>
</head>
http://www.oracle.com/technetwork/java/javaee/javaee-faq-jsp-135209.html#diff
JavaBeans
• manage the data flow between the following:
Client/Database Server
application client or applet components running on the
Java EE server
NameHandler.java
Class NameHandler
containing user data
GlassFish Server
Web profile
Java Application Server: Glassfish
GlassFish
is an open source application server project led by Sun
Microsystems for the Java EE platform. The proprietary
version is called Oracle GlassFish Enterprise Server.
GlassFish is free software
Sun is the original creator
of Tomcat
It uses a derivative of Apache Tomcat as the servlet
container for serving Web content, with an added
component called Grizzly which uses Java NIO for scalability
and speed.
https://grizzly.dev.java.net/ http://java.dzone.com/articles/glassfish-and-tomcat-whats-the
Before the advent of the Java New I/O API (NIO), thread
management issues made it impossible for a server to
scale to thousands of users
Java Application Server: Glassfish
GlassFish is an open source (full) application server project led by Sun
Microsystems for the Java EE platform. The proprietary version is
called Oracle GlassFish Enterprise Server. GlassFish is free software.
http://www.jsptut.com/Getfamiliar.jsp
Commercial Deployment
Oracle provides software support only
• Oracle GlassFish Server for Oracle GlassFish Server, not for
GlassFish Server Open Source Edition
–delivers a flexible, lightweight and extensible Java EE 6
platform. It provides a small footprint, fully featured
Java EE application server that is completely supported
for commercial deployment and is available as a
standalone offering.
• Oracle WebLogic Server
–designed to run the broader portfolio of Oracle Fusion
Middleware and large-scale enterprise applications.
–industry's most comprehensive Java platform for
developing, deploying, and integrating enterprise
applications.
http://docs.sun.com/app/docs/doc/821-1751/gkbtb?l=en&a=view
Creating a new Web Application
JSP File
Creating a new Web Application
Sample Run
Project: HelloWeb
HelloWeb: Directories and Files
NameHandler.java
Java Package
Right-click Source Packages
http://en.wikipedia.org/wiki/GlassFish
Java Package
Add a Java Class, specify Package name
Java Package
• a mechanism for organizing Java classes into namespaces
• can be stored in compressed files called JAR files, allowing classes to
download faster as a group rather than one at a time.
http://en.wikipedia.org/wiki/GlassFish
Java Package
Add a Java Class
http://en.wikipedia.org/wiki/GlassFish
Java Package
Edit the Java Class
http://en.wikipedia.org/wiki/GlassFish
Generating Getter and Setter Methods
Right-click name field in the Source editor
Notice that Fields' Visibility is by default set to private, and Accessors' Visibility to
public, indicating that the access modifier for class variable declaration will be
specified as private, whereas getter and setter methods will be generated with
public and private modifiers, respectively.
Generating Getter and Setter Methods
expand HTML Forms and drag a Form item to a point after the <h1> tags in
the Source Editor.
Click OK.
Source Generated
Drag a Text Input item to a point just before the </form> tag, then specify
the following values:
• Name: name
• Type: text
Source Generated
Drag a Button item to a point just before the </form> tag. Specify the
following values:
• Label: OK
• Type: submit
Type Enter your name: just before the first <input> tag, then change
the default Hello World! text between the <h1> tags to Entry Form.
We would like to
pass this to our
server
response.jsp
Adding a JSP File
In the Projects window, right-click the HelloWeb project node and choose
New > JSP. The New JSP File wizard opens.
Notice that a response.jsp file node displays in the Projects window beneath
index.jsp, and the new file opens in the Source Editor.
JSP Source File Generated: response.jsp
Adding a Use Bean item
In the Palette to the right of the Source Editor, expand JSP and drag a Use
Bean item to a point just below the <body> tag in the Source Editor.
Notice that the <jsp:useBean> tag is added beneath the <body> tag.
Adding a Set Bean property item
Drag a Set Bean Property item from the Palette to a point just before the
<h1> tag and click OK.
In the <jsp:setProperty> tag that appears, delete the empty value attribute
and edit as follows. Delete the value = "" attribute if the IDE created it!
Otherwise, it overwrites the value for name that you pass in index.jsp.
Adding a Set Bean property item
Drag a Set Bean Property item from the Palette to a point just before the
<h1> tag and click OK.
In the <jsp:setProperty> tag that appears, delete the empty value attribute
and edit as follows. Delete the value = "" attribute if the IDE created it!
Otherwise, it overwrites the value for name that you pass in index.jsp.
Adding a Get Bean property item
Drag a Get Bean Property item from the Palette and drop it after the comma
between the <h1> tags.
Specify the following values in the Insert Get Bean Property dialog:
• Bean Name: mybean
• Property Name: name
Therefore, by setting property to name, you can retrieve the value specified by
user input.
Sample Run
User input
Response from
the JSP file
Sample Run
NameHandler.java
Class NameHandler
containing user data, get
and set methods
http://java.sun.com/blueprints/code/projectconventions.html
http://java.sun.com/blueprints/code/projectconventions.html
NetBeans
http://netbeans.org/kb/docs/web/quickstart-webapps.html
http://www.oracle.com/technetwork/java/javaee/documentation/index.html
Simple Database Example
http://netbeans.org/kb/docs/web/mysql-webapp.html
E-Commerce Example
http://netbeans.org/kb/docs/javaee/ecommerce/design.html
http://netbeans.org/kb/docs/javaee/ecommerce/data-model.html#createERDiagram
http://dot.netbeans.org:8080/AffableBean/
Model-View-Controller Paradigm
V. Tecnologías
Java EE
V. Tecnologías Java EE
Tecnologías Vista: JSF
Estándar SUN: Existen muchas alternativas.
Comunidad de desarrollo amplia.
Apoyo tecnológico de las principales compañías.
Adaptación de las mejores ideas de otros.
Lentitud en asimilar nuevas tecnologías.
Modificaciones o mejoras lentas.
Dependencia de implementaciones de terceros.
V. Tecnologías Java EE
Tecnologías Vista: JSF
Componentes de JSF:
API + Implementación de Referencia.
Representan componentes UI y manejan su estado, eventos,
validaciones, navegación, etc…
Librería de Etiquetas.
Etiquetas personalizadas de JSP para dibujar los componentes UI dentro
de las páginas JSP.
V. Tecnologías Java EE
Ciclo de Vida JSF
Las peticiones Faces no se limitan a petición-respuesta,
disponen de un ciclo de vida.
El ciclo de vida depende del tipo de petición.
Respuesta No-Faces: Respuesta generada al margen de la fase de
renderizar respuesta de faces.
Respuesta Faces: Respuesta generada en la fase de renderizar
respuesta de faces.
Petición No-Faces: Petición enviada a un componente no faces.
Petición Faces: Petición enviada desde una respuesta faces
previamente generada.
El escenario normal Peticion faces/Respuesta faces.
V. Tecnologías Java EE
Ciclo de Vida JSF
V. Tecnologías Java EE
Ciclo de Vida JSF
Reconstruir el árbol de componentes.
Se construye el árbol de componentes faces.
Aplicar valores a la petición.
Se asocian a los componentes los nuevos valores desde los
parámetros de la petición.
Procesar validaciones.
Se procesan las validaciones para los componentes.
Actualizar los valores del modelo.
Una vez es válido se actualizan los valores del modelo.
Invocar aplicación.
En este punto se manejan los eventos a nivel de aplicación.
Renderizar respuesta.
Por último se dibujan los componentes del árbol.
V. Tecnologías Java EE
Componentes JSF
Conjunto de clases UIComponent.
Representan los componentes.
Modelo de renderizado.
Forma de visualizar el componente.
Modelo de eventos.
Forma de manejar los eventos lanzados.
Modelo de conversión.
Conectar conversores de datos al componente.
Modelo de validación.
Forma de registrar validadores para el componente.
Se emplean las etiquetas.
RichFaces, ICEFaces: Librerías de etiquetas.
V. Tecnologías Java EE
Componentes JSF
<h:dataTable id="noticias" value="#{Noticias.listadoCategoria}" var="noti">
<h:column>
<f:facet name="header"><h:outputText value="Titular"/></f:facet>
<h:outputText value="#{noti.titulo}" />
</h:column>
<h:column>
<f:facet name="header"><h:outputText value="Contenido"/></f:facet>
<h:outputText value="#{noti.contenido}" />
</h:column>
http://java.sun.com/javaee/javaserverfaces/reference/docs/
</h:dataTable>
---------------------------------------------------------------------------------------------------------------------------------------------------------------
http://java.sun.com/javaee/javaserverfaces/1.2/docs/tlddocs/
<h:form id=“NoticiaForm”>
<h:outputText value="Código:"/>
<h:inputText id="codigo" value="#{GestorNoticias.noticia.codigo}" required="true" /><br/>
http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/api/index.html
<h:outputText value="Titulo:"/>
<h:inputText id="titulo" value="#{GestorNoticias.noticia.titulo}" required="true" /><br/>
<h:outputText value="Contenido:"/>
<h:inputText id="contenido" value="#{GestorNoticias.noticia.contenido}" required="true" /><br/>
<h:outputText value="Fecha:"/>
<h:inputText id="fecha" value="#{GestorNoticias.noticia.fecha}" required="true">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText><br/>
<h:outputText value="Portada:"/>
<h:selectBooleanCheckbox id="portada" value="#{GestorNoticias.noticia.portada}" required="true" /><br/>
<h:outputText value="Categoria:"/>
<h:selectOneMenu id="categoria" value="#{GestorNoticias.categoriaId}">
<f:selectItems value="#{GestorNoticias.selectCategorias}" />
</h:selectOneMenu><br/>
<h:commandButton value="Guardar" action="#{GestorNoticias.saveNoticia}" />
</h:form>
V. Tecnologías Java EE
Faces-Config.xml
Archivo de configuración principal.
Describe los bean manejados.
<managed-bean>
<description>Noticiero</description>
<managed-bean-name>GestorNoticias</managed-bean-name>
<managed-bean-class>web.GestorNoticias</managed-bean-class>
<managed-bean-scope>application/session/request/none</managed-bean-scope>
<context-param>
Describe
</managed-bean>
las reglas de navegación.
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml,/WEB-INF/faces-beans.xml</param-value>
</context-param>
<navigation-rule>
<from-view-id>/editar/editar.xhtml</from-view-id>
<navigation-case>
<from-outcome>nuevaCategoria</from-outcome>
<to-view-id>/editar/new/categoria.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>nuevaNoticia</from-outcome>
<to-view-id>/editar/new/noticia.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
V. Tecnologías Java EE
JSF Paso a Paso
Ciclo de Vida
Podemos crear un Listener.
Escucha la fase indicada en getPhaseId.
/WEB-INF/faces-config.xml
<lifecycle>
<phase-listener>lst.PhaseListener</phase-listener>
</lifecycle>
V. Tecnologías Java EE
JSF Paso a Paso
Mapear Componentes Con Objetos
Mapear Valores Fijos
<h:outputText value=“Hola Mundo !!"/>
Mapear Propiedades del Sistema
<h:outputText value=“#{initParam.version}"/>
<h:outputText value=“#{param[‘nombre’]}"/>
Mapear Propiedades de un Bean Manejado
Siguen convenciones JavaBean.
<h:outputText value="#{managedBeans.propiedad}"/>
<managed-bean>
<managed-bean-name>managedBeans</managed-bean-name>
<managed-bean-class>mbeans.ManagedBeans</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>propiedad</property-name>
<value>Hola Mundo !!</value>
</managed-property>
</managed-bean>
V. Tecnologías Java EE
JSF Paso a Paso
Mapear Componentes
Mapear Componentes Completos Backing Beans
<h:outputText binding="#{managedBeans.component}"/>
package mbeans;
import javax.faces.component.UIOutput;
public class ManagedBeans {
private UIOutput component;
public void setComponent(UIOutput ui) {
component = ui;
component.setValue("Hola Mundito !!");
}
public UIOutput getComponent() { return component; }
}
V. Tecnologías Java EE
JSF Paso a Paso
Invocar Métodos
Métodos de Validación
Utilizados sólo en UIInput.
Reciben el FacesContext y el componente a validar y su valor.
<h:messages/>
<h:inputText validator="#{managedBeans.validateEmail}"/>
public void validateEmail(FacesContext ctx, UIComponent cmp, Object obj) {
String email = (String)obj;
if (email.indexOf("@")<0) {
((UIInput)cmp).setValid(false);
ctx.addMessage(cmp.getClientId(ctx),
new FacesMessage("Mail Incorrecto", ""));
} else ((UIInput)cmp).setValid(true);
}
V. Tecnologías Java EE
JSF Paso a Paso
Invocar Métodos
Manejadores de Acciones
Se utiliza en UICommand y UIButton.
Reciben el evento.
<h:selectBooleanCheckbox
valueChangeListener="#{managedBeans.changeColor}"
onchange="submit()"/>
<navigation-rule>
<from-view-id>/logon.jsp</from-view-id>
<navigation-case>
<from-action>#{LogonForm.logon}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/continue.jsp</to-view-id>
</navigation-case>
</navigation-rule>
V. Tecnologías Java EE
JSF Paso a Paso
Controlar Navegación. Ejemplos.
<navigation-rule>
<from-view-id>/pages/logon.jsp</from-view-id> Enlace en /pages/logon.jsp Destino
<navigation-case>
<from-outcome>success</from-outcome> <h:commandButton action=“success" value="Submit" /> continue1.jsp
<to-view-id>/continue1.jsp</to-view-id> <h:commandButton action=“#{m.acc}" value="Submit" /> continue2.jsp
</navigation-case>
<navigation-case> <h:commandButton action=“error" value="Submit" /> error.jsp
<from-action>#{m.acc}</from-action>
<from-outcome>success</from-outcome>
Enlace en /pages/otra.jsp Destino
<to-view-id>/continue2.jsp</to-view-id>
</navigation-case>
<h:commandButton action=“success" value="Submit" /> continue3.jsp
</navigation-rule>
<h:commandButton action=“#{m.acc}" value="Submit" /> continue3.jsp
<navigation-rule>
<from-view-id>/pages/*</from-view-id> <h:commandButton action=“error" value="Submit" /> error.jsp
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/continue3.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<navigation-case>
<from-outcome>error</from-outcome>
<to-view-id>/error.jsp</to-view-id>
</navigation-case>
</navigation-rule>
V. Tecnologías Java EE
JSF Paso a Paso
Crear el adivinador de números JSF.
Crear un bean para calcular el número aleatorio.
El mismo bean puede recoger el número introducido.
Crea el JSP para solicitar el número, valida la entrada con validateLongRange.
Configura la navegación adecuada.
V. Tecnologías Java EE
Crea un Hola Mundo JSF.
V. Tecnologías Java EE
Crea un Hola Mundo JSF.
V. Tecnologías Java EE
JSF Paso a Paso
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@
Crear
taglibel adivinador
prefix="f"
Internacionalizar de números JSF.
uri="http://java.sun.com/jsf/core"%>
i18n
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<application>
<html> <locale-config>
<managed-bean>
<head>
public class<default-locale>es</default-locale>
Adivina {
<%@ <managed-bean-name>adivina</managed-bean-name>
<metapage language="java"
http-equiv="Content-Type" contentType="text/html;
content="text/html;charset=ISO-8859-1"
<supported-locale>en</supported-locale> charset=ISO-8859-1">pageEncoding="ISO-8859-1"%>
<%@ <managed-bean-class>mbeans.Adivina</managed-bean-class>
taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<title>Insert title here</title>
private
</locale-config> long numeroPensado;
<%@ <managed-bean-scope>session</managed-bean-scope>
taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
</head> private int numero;
<message-bundle>msg.mensajes</message-bundle>
<!DOCTYPE <managed-property>
html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<body> private int minimo;
<resource-bundle>
<html> <property-name>minimo</property-name>
<f:view> private int maximo;
<base-name>msg.mensajes</base-name>
<head> <value>1</value>
<h:outputText
<var>msg</var> rendered="#{adivina.intentado}" value="Lo siento, vuelve a probar !!"/>
</managed-property>content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Type"
He pensado un número entre <h:outputText
public Adivina() { numeroPensado
</resource-bundle> value="#{adivina.minimo}"/>
= Math.round(Math.random()*10); } y
<managed-property>
<title>Insertpublic
title here</title>
</application> int getNumero() <h:outputText
{ return numero; } value="#{adivina.maximo}"/>, adivina !!
</head> <property-name>maximo</property-name>
<h:form>public void setNumero(int n) { numero = n; }
<body> <value>10</value>
<f:loadBundle <h:messages
public int showDetail="true"/>
basename="msg.mensajes"
getMinimo() { return var="msg"/>
minimo;}
<f:view> </managed-property>
<h:messages <h:selectOneMenu
showDetail=“true”
public void setMinimo(int onchange="submit()"
showSummary=“true”/>
minimo) { this.minimo = minimo; }
</managed-bean> Has acertado, era el <h:outputText value="#{adivina.numero}"/> !!
<h:outputText valueChangeListener="#{adivina.cambiaIdioma}"
value="#{msg.titulo}"/>
public int getMaximo() { return maximo; } immediate="true">
<navigation-rule>
</f:view> public void setMaximo(int <f:selectItem itemLabel="#{msg.castellano}"
maximo) {this.maximo = maximo; }itemValue="es"/>
</body> <from-view-id>/index.jsp</from-view-id>
Archivo de Propiedades:
public <f:selectItem
String adivinar() { returnitemLabel="#{msg.ingles}"
msg/mensajes.properties, itemValue="en"/>
msg/mensajes_en.properties,
(numeroPensado==numero)? "success“:"fail"; } …
</html> <navigation-case>
</h:selectOneMenu>
public boolean<from-outcome>success</from-outcome>
isIntentado() { return numero!=0; }
<h:inputText
publicenvoid value="#{adivina.numero}">
titulo=Pienso un cambiaIdioma(ValueChangeEvent
número event) {
entre minimum="#{adivina.minimo}"
<to-view-id>/next.jsp</to-view-id>
<f:validateDoubleRange maximum="#{adivina.maximo}"/>
FacesContext.getCurrentInstance().getViewRoot().setLocale(new
</navigation-case>
javax.faces.validator.DoubleRangeValidator.NOT_IN_RANGE=Sumario Locale((String)event.getNewValue()));
</h:inputText>
// Cortocircuito !!
<navigation-case>
javax.faces.validator.DoubleRangeValidator.NOT_IN_RANGE_detail=Valor fuera de rango {0} - {1}.
<h:commandButton value="Prueba" action="#{adivina.adivinar}"/>
FacesContext.getCurrentInstance().renderResponse();
<from-outcome>fail</from-outcome>
</h:form>
} <to-view-id>/index.jsp</to-view-id>
} </f:view>
</navigation-case>
</body>
</navigation-rule>
</html>
V. Tecnologías Java EE
Facelets
Complemento ideal para JSF.
Definir una plantilla para tu portal y emplearla en todas tus páginas.
<ui:include src=“cabecera.xhtml”/>
<ui:insert name=“body”/>
/pagina.xhtml
<ui:composition template=“/plantilla.xhtml”>
<ui:include <ui:define name=“body”>
src=“menu.xhtml”/>
…
</ui:define>
</ui:composition>
<ui:include src=“pie.xhtml”/>
V. Tecnologías Java EE
Crea una plantilla facelets.
Añadir la librería Facelets:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html jsf-facelets-1.1.15.B1.jar
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
Debemos
Nota: web.xml cambiar
y faces-config.xml los las vistas
modifica y las!!reglas del faces-
eclipse
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
config.xml los id de
xmlns:h="http://java.sun.com/jsf/html" las vistas pasan de .jsp a
xmlns:f="http://java.sun.com/jsf/core">
.xhtml.
<f:view contentType="text/html"/>
<head>
<meta http-equiv="Content-Type" content="text/xhtml+xml; charset=UTF-8" />
<title>Simple JSF</title>
<link href="stylesheet/theme.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="content">
<div id="header"><ui:include src="header.xhtml" /></div>
<div id="menu" style="float:left;width:200px;"><ui:include src="menu.xhtml" /></div>
<div id="body" style="float:left;"><ui:insert name="body" >Default Content</ui:insert></div>
<div id="footer"><ui:include src="footer.xhtml" /></div>
</div>
</body>
</html>
V. Tecnologías Java EE
Usar RichFaces.
<!-- RichFaces en web.xml -->
<context-param>
<param-name>org.richfaces.SKIN</param-name>
Para Usar RichFaces Añadir Librerías:
<param-value>blueSky</param-value>
</context-param>
<!-- RichFaces + Facelets -->
commons-beanutils-1.7.0.jar
<context-param>
<?xml version="1.0" encoding="UTF-8"?>
commons-digester-1.8.jar <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name>
<html … xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
<param-value>com.sun.facelets.FaceletViewHandler</param-value>
<body bgcolor="white">
</context-param>
commons-logging-1.1.1.jar
…
<filter>
<rich:panel id="panelRoot" >
<display-name>RichFaces Filter</display-name>
richfaces-api-3.3.1.GA.jar
<rich:spacer height="5" title="Here is a spacer..."/><br />
<filter-name>richfaces</filter-name>
<rich:separator lineType="beveled" height="8" width="100%" align="center"/>
<filter-class>org.ajax4jsf.Filter</filter-class>
richfaces-impl-3.3.1.GA.jar
<rich:separator height="2" lineType="dotted"/><br />
</filter>
</rich:panel>
<filter-mapping>
richfaces-ui-3.3.1.GA.jar
…
<filter-name>richfaces</filter-name>
</body>
Nota: Hay que configurar a <servlet-name>Faces
</html> mano !! Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
Y muchos componentes más: RichFaces Live Demo.
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
@Stateless
public class PlaceBidBean implements PlaceBid {
@Interceptors(ActionBazaarLogger.class)
public void addBid(Bid bid) {
...
}
}
Página
--------------------------------------------------------------------------------------
<h:outputText value="#{jSFBean.mensaje}" />
V. Tecnologías Java EE
Crea un EJB.
V. Tecnologías Java EE
Tecnologías Modelo: JPA
Muchos proyectos diferentes ORM.
IBatis, Hibernate, JDO, TopLink,…
Necesario unificar: JPA.
V. Tecnologías Java EE
Tecnologías Modelo: JPA
Contextos de Persistencia
@NamedNativeQuery (
name="nativeResult",
query="SELECT USUARIO_ID,NOMBRE,APELLIDOS FROM USUARIOS WHERE USUARIO_ID= 123",
resultSetMapping = "usuarioNamedMapping")
@SqlResultSetMapping (
name="usuarioNamedMapping",
entities = { @EntityResult (
entityClass = mi.clase.Usuario.class,
fields = {@FieldResult (
name="usuarioId",
column="USUARIO_ID"),
@FieldResult (
name="nombre",
column="NOMBRE"),
@FieldResult (
name="apellidos",
column="APELLIDOS")
})
})
V. Tecnologías Java EE
Tecnologías Modelo: JPA
Anotaciones Avanzadas: Procedimientos Almacenados
<security-role>
<role-name>administrador</role-name>
</security-role>
<security-role>
<role-name>usuario</role-name>
</security-role>
<orion-application …>
...
<jazn provider="XML" location="./jazn-data.xml" default-realm="example.com">
<property name="jaas.username.simple" value="false"/>
</jazn>
</orion-application>
<jazn-data
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://xmlns.oracle.com/oracleas/schema/jazn-data-10_0.xsd" filepath="" OC4J_INSTANCE_ID="">
<jazn-realm>
<realm>
<name>example.com</name>
<users><user><name>admin</name><credentials>!admin</credentials></user></users>
<roles>
<role><name>administrador</name><members><member><type>user</type><name>admin</name></member></members></role>
</roles>
</realm>
</jazn-realm>
</jazn-data>
VI. Tecnologías Avanzadas
Autenticación JAAS
Java EE permite emplear roles para securizar recursos de una aplicación.
@DeclareRoles({"administrador", "usuario"})
public class Ejemplo extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if (req.isUserInRole("administrador")) {
// El usuario Autenticado tiene el rol administrador
}
}
}
<security-constraint>
<web-resource-collection>
<web-resource-name>Permiso Ejemplo</web-resource-name>
<url-pattern>/Ejemplo</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>administrador</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!-- LOGIN CONFIGURATION-->
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
VI. Tecnologías Avanzadas
Prácticas II
Crea roles en una aplicación.
Añade seguridad a diferentes recursos.
Securiza la creación de noticias en el Diario Digital.
VI. Tecnologías Avanzadas
Crea roles en una aplicación.
<!-- ROLES DE SEGURIDAD -->
<security-role>
<role-name>redactor</role-name> <wls:security-role-assignment>
</security-role> <wls:role-name>redactor</wls:role-name>
<security-role>
<wls:principal-name>Administrators</wls:principal-name>
<role-name>usuario</role-name>
</security-role> </wls:security-role-assignment>
<security-constraint> <wls:security-role-assignment>
<web-resource-collection> <wls:role-name>usuario</wls:role-name>
<wls:principal-name>AppTesters</wls:principal-name>
<web-resource-name>Redaccion del Diario</web-resource-name>
<url-pattern>/editar/*</url-pattern> </wls:security-role-assignment>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>redactor</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!-- LOGIN CONFIGURATION-->
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
VI. Tecnologías Avanzadas
Portales y Portlets
Idea similar a la de los servlets.
Componentes configurables y reubicables.
Pensados para su uso en portales.
Especificación JSR 168.
VI. Tecnologías Avanzadas
Portales y Portlets
Ventajas
Desarrollo independiente y reutilizable.
Personalización dinámica.
Seguridad ante fallos. El fallo de un portlet no afecta al resto del portal.
Adoptado por otras tecnologías. PHP Portlet.
Inconvenientes
Tecnología relativamente nueva.
Genera portales con poca personalidad.
A. Diario Digital
A. Diario Digital
Práctica Global
Muestra las noticias de un diario y un teletipo.
EAR Application
EJB Module
Database
¡ Gracias !