taller integracion jsf spring

Post on 14-Jun-2015

6.587 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Configuración de un ambiente de desarrollo con Prime faces (JSF), Spring, maven

TRANSCRIPT

Taller Spring + Prime FacesEduardo Granados

Correo: odraudek99@gmail.com

Herramientas

Eclipse IDE o STS Maven >= 3.0 Servidor de aplicaciones (vMware vFabric). Spring 3.1.x PrimeFaces 3.0 JDK >= 1.6.0

Creación del Proyecto Maven

Crear un Nuevo Proyecto tipo Maven

Creación del Proyecto Maven

En el IDE (STS o Eclipse) Crear un Nuevo Proyecto tipo Maven

Creación del Proyecto Maven

Dar click en “Siguiente” y se selecciona: “Create a simple project”, esto creara un proyecto vacío de Maven

Creación del Proyecto Maven

Dar click en “siguiente”. Llenamos los campos:

GroupId ArtifactId Packaging

Finalizar

Estructura Proyecto Maven

Al terminar se mostrará el proyecto “jsf-spring” con la siguiente estructura:

Estructura Proyecto Maven

Maven tiene cuatro carpetas por default: Src/main/java:

Aqui se guardan las clases Java, debajo de esta se agregan los paquetes requeridos.

Src/main/resources Aqui se guardan los recursos (configuraciones xml, imagenes).

Src/test/java Aqui se almacenan clases para realizar test al código fuente.

Src/test/resources Almacena recursos para los test.

Archivo POM.xml (Project Object Model)

Archivo POM

El contenido inicial del pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion> <groupId>taller.java</groupId> <artifactId>jsf-spring</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging></project>

Probando el Proyecto Simple

Para validar que el proyecto levanta vamos a crear una página simple, para ello debemos crear lo siguiente: Dentro de src/main/webapp crear un directorio

llamado “WEB-INF”. Dentro de WEB-INF crear un archivo xml llamado

“web.xml”.

Probando el Proyecto Simple

La estructura del proyecto debe quedar como se muestra:

Probando el Proyecto Simple

Agregamos el siguiente contenido al archivo web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="SPI" version="2.5"><display-name>jsf-spring</display-name>

<welcome-file-list><welcome-file>hola.html</welcome-file>

</welcome-file-list></web-app>

Probando el Proyecto Simple

Dentro de webapp creamos una página html simple, llamada: “hola.html” y Finalizamos

Probando el Proyecto Simple

Nuestro html simple puede quedar asi:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h1>Hola Mundo</h1></body></html>

Probando el Proyecto Simple

Guardamos el proyecto y ejecutamos el proyecto en el servidor: Click derecho en el

Proyecto Run As/ Run on Server

Damos y damos click

en Finalziar.

Probando el Proyecto Simple

Abrimos un navegador de Internet y entramos a: http://localhost:8080/jsf-spring/ nos debe mostrar:

Probando el Proyecto Simple

Con esto hemos logrado arrancar una aplicación simple de HTML con Maven

Segunda Parte

Ahora continuaremos con la configuración de nuestro proyecto con la integración de Spring y PrimeFaces.

Para ello debemos detener el servidor de aplicaciones.

Configurando Prime Faces

Agregamos las siguientes propiedades al archivo pom.xml

<properties><primefaces-version>3.4</primefaces-version></properties>

Configurando Prime Faces

Se agrega el repositorio de PrimeFaces:

<repositories><repository>

<id>prime-repo</id><name>PrimeFaces Maven Repository</name><url>http://repository.primefaces.org</url><layout>default</layout>

</repository></repositories>

Configurando Prime Faces

Se agregan las dependencias de PrimeFaces:

(1/2)

<dependency><groupId>org.primefaces</groupId><artifactId>primefaces</artifactId><version>${primefaces-version}</version>

</dependency>

<!-- JSF dependencies --><dependency>

<groupId>com.sun.faces</groupId><artifactId>jsf-api</artifactId><version>2.1.6</version>

</dependency>

Configurando Prime Faces

Se agregan las dependencias de PrimeFaces:

(2/2)

<dependency><groupId>com.sun.faces</groupId><artifactId>jsf-impl</artifactId><version>2.1.6</version>

</dependency>

<dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version>

</dependency>

Configurando Prime Faces

El contenido del archivo web.xml se cambia por lo siguiente (1/2):

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="SPI" version="2.5">

<display-name>jsf-spring</display-name>

<welcome-file-list><welcome-file>hola.xhtml</welcome-file>

</welcome-file-list>

Configurando Prime Faces

El contenido del archivo web.xml se cambia por lo siguiente (2/2):

<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>*.xhtml</url-pattern>

</servlet-mapping></web-app>

Configurando Prime Faces

Creamos la clase Java “MiControlador.java” con el siguiente contenido, en el paquete “jsfspring”, agregar sets y gets de nombre y saludo.

@ManagedBean(name = "miControlador")@ViewScopedpublic class MiControlador implements Serializable {

private static final long serialVersionUID = 1L;

private String nombre;private String saludo;

public void saluda() {if (nombre != null) {

saludo = "Hola " + nombre;} else {

saludo = "hola tú";}

}

}

Configurando Prime Faces

Creamos el archivo de configuración de JSF, un xml en src/main/resources llamado: “faces-config.xml” ya agregamos el siguiente contenido:

<?xml version="1.0" encoding="UTF-8"?><faces-config xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

version="2.0">

</faces-config>

Configurando Prime Faces

Creamos un archivo llamado “hola.xhtml” en scr/main/webapp y le agregamos el siguiente contenido:

<!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" xmlns:p="http://primefaces.org/ui"><h:head></h:head><h:body>

<h:form id="form"><h:panelGrid columns="2">

<h:outputLabel value="Nombre: " for="nombre" /><p:inputText value="#{miControlador.nombre}" id="nombre" title="nombre"

required="true"/></h:panelGrid><p:inputText value="#{miControlador.saludo}" readonly="true"/><h:commandButton value="Saluda" actionListener="#{miControlador.saluda}"/>

</h:form></h:body></html>

Configurando Prime Faces

Levantamos el Proyecto: Click derecho en el proyecto Run As/Maven Clean Run As/Maven Install Run As/Run on server Ingresamos a

http://localhost:8080/jsf-spring/hola.xhtml

Configurando Prime Faces

Probamos nuestra pantalla:

Configurando Prime Faces

Hemos logrado crear y correr nuestro proyecto web con PrimeFaces, ahora agregaremos spring framework para inyección de dependencias.

Configurando Spring Framework

Para agregar las dependencias de spring abrimos nuestro archivo pom.xml y agregamos la siguiente propiedad:

<spring-version>3.1.1.RELEASE</spring-version>

Configurando Spring Framework

Agregamos las siguientes dependecias en el pom.xml

<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring-version}</version></dependency>

<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring-version}</version></dependency>

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring-version}</version> </dependency>

Configurando Spring Framework

Creamos la Interfaz “NegocioBean” dentro del paquete “jsfspring.negocio”

package jsfspring.negocio;

public interface NegocioBean {

public String saluda(String nombre);}

Configurando Spring Framework

Creamos la clase: NegocioBeanImpl.java en el paquete: jsfspring.negocio.impl

package jsfspring.negocio.impl;import java.io.Serializable;import jsfspring.negocio.NegocioBean;public class NegocioBeanImpl implements NegocioBean, Serializable {private static final long serialVersionUID = 1L;

public String saluda(String nombre) {if (nombre != null) {

return "Hola " + nombre;}return "hola tú";

}}

Configurando Spring Framework

Agregamos las siguientes lineas al web.xml<context-param><param-name>contextConfigLocation</param-name><param-value> /WEB-INF/applicationContext.xml</param-value></context-param>

<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener>

Configurando Spring Framework

Al archivo faces-config.xml<application><!-- Spring --><el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver></application>

Configurando Spring Framework

Dentro de src/main/webapp/WEB-INF creamos un archivo llamado “applicationContext.xml”, con el contenido siguiente:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<context:annotation-config /><context:component-scan base-package="jsfspring.negocio.impl" /><bean id="negocioBean" class="jsfspring.negocio.impl.NegocioBeanImpl" />

</beans>

Configurando Spring Framework

Modificamos nuestro controlador de la página, agregando:

@ManagedProperty(value = "#{negocioBean}")private NegocioBean negocioBean;

Modificamos el método saluda():public void saluda() {

saludo = negocioBean.saluda(nombre);}

Agregar los métodos set y get de negocioBean

Configurando Spring Framework

Configurando Spring Framework

Levantamos el Proyecto: Click derecho en el proyecto Run As/Maven Clean Run As/Maven Install Run As/Run on server Ingresamos a

http://localhost:8080/jsf-spring/hola.xhtml

Configurando Spring Framework

Probamos nuestra pantalla:

Código Fuente Completo

Se adjunta el código completo del ejemplo:

jsf-spring.rar

INTEGRACIÓN

MAVEN + PRIMEFACES + SPRING.

GRACIAS.

Eduardo Granados.

odraudek99@gmail.com

top related