Beruflich Dokumente
Kultur Dokumente
Agenda
Introduo
Necessidade de Templating
JSF normalemte evita JSP tags Mesmo se usar o jsp:include, haver problemas
Sem templates reais ou sees nomeadas No pode passar dados fcil para as pginas includasCant easily pass data to included pages
The JSF 1.x model for making custom components was ridiculously complicated. Facelets in JSF 2.0 provide a relatively simple way to make many of those components.
Vantagens do Facelet
Templating Real
Arquivos template definem um layout e sees Arquivos Clientes usam o template e substituem as sees Pode passar dados do JSF para pginas includas Sintaxe XML ajuda no desenvolvimento xhtml syntax checking for result Pode usar #{blah} ou ${blah} em qualquer lugar @taglib e f:view no necessrio
JSP 2.1 EL
Sucinta
JSF 1.x h necessidade de instalar as bibliotecas do Facelet JSF 2.0 j vem como padro Necessidade para criao de componentes complexos
No JSF 1.x era extremamente complicado a criao de componente. Facelets no JSF 2.0 prov um modo simples de criar tais componentes
jsf-facelets.jar, el-api.jar, el-ri.jar Download em http://facelets.dev.java.net/ Obrigatrio: javax.faces.DEFAULT_SUFFIX Opcional mas que ajuda
facelets.REFRESH_PERIOD facelets.DEVELOPMENT
com.sun.facelets.FaceletViewHandler
Web.xml
<web-app ...> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param>
Qual frequencia checar por mudanas Extenso dos arquivos facelets E.x., foo.xhtml ser acessado como foo.faces.
<context-param> <param-name>facelets.REFRESH_PERIOD</param-name> <param-value>2</param-value> </context-param> <context-param> <param-name>facelets.DEVELOPMENT</param-name> <param-value>true</param-value> </context-param> ... </web-app>
faces-config.xml
<faces-config> <application> <view-handler> com.sun.facelets.FaceletViewHandler </view-handler> </application> ... </faces-config>
Passos Bsicos
Contedo que aparece para todos os clientes pode ser colocado diretamente no template Contedo que ser substitudo por arquivos clientes marcado com ui:insert (com um valor default em caso do cliente no inserir algum contedo)
Usar ui:composition para especificar qual template usado Usar ui:define para sobrescrever o contedo de cada seo no template (marcado no template com ui:insert) http://host/app/clientfile.jsf
Exemplo Simplificado
...
/templates/template-1.xhtml
<h:body>Content shared by all client files <h2><ui:insert name="title">Default Title</ui:insert></h2> More content shared by all clients <ui:insert name="body">Default Body</ui:insert> </h:body> ...
<ui:composition template="/templates/template-1.xhtml"> <ui:define name="title">Title text</ui:define> <ui:define name="body"> Content to go in "body" section of template </ui:define></ui:composition>
Substitui o contedo padro do title do template. Se omitido o do template assume.
client-file-1.xhtml
Arquivo Template
Namespaces
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"> </html> Se usar outra bibliotecas de tags (f, c, etc.), lista elas tambm <html xmlns="http://www.w3.org/1999/xhtml"
Arquivo Template
Se tem algum HTML ou JSF que ser usado por todos os clientes, coloque-o diretamente no template
D um nome a seo (cliente referenciar o nome) Coloque um valor default <ui:insert...> and </ui:insert> Ou use <h:outputText value="#{blah}" /> se precisar de alguma das opes do h:outputText
Template: Exemplo
(/templates/sample-template.xhtml)
<!DOCTYPE ...> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"> <h:head> <title> <ui:insert name="title">Default Title</ui:insert> </title> <link rel="stylesheet" type="text/css" href="./css/styles.css"/> Essas sees As partes no marcadas com podem ser </h:head> ui:insert iro aparecer em todos os substitudas no arquivos clientes carquivo cliente <h:body> <table border="5" align="center"><tr><th class="title"> <ui:insert name="title">Default Title</ui:insert> </th></tr></table> <h2>A random number: #{numGenerator.randomNum}</h2> <ui:insert name="content">Default Content</ui:insert> </h:body></html>
Bean
package coreservlets; import javax.faces.bean.*; @ManagedBean public class NumGenerator { public double getRandomNum() { return(Math.random()); } }
<ui:composition xmlns="" xmlns:ui="" template="/templates/some-template.xhtml"> <ui:define name="section-name-from-template-file"> Content to be inserted into section. XHTML tags, JSF tags, EL expressions, etc. </ui:define> Precisa ser acessvel
Client : Exemplo
(/sample-page.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="/templates/sample-template.xhtml"> <ui:define name="title"> This is the new title </ui:define> <ui:define name="content"> This is the new content. <p/> Blah, blah, blah. Yadda, yadda, yadda. </ui:define> </ui:composition>
Cliente Resultado
Motivao
Problemas No pode ser inserido diretamente no template Usado por mais de um cliente ento dificil e repetitivo usar o ui:define no arquivo cliente Soluo Colocar contedo reusavel em arquivos separados
Usando ui:include
Opes
Template
Inserir contedo compartilhado Marcar sees a serem substitudas com o ui:insert Sadas dinmicas com #{blah} Colocar em uma pasta separada
Contedo no ui:composition
Com as referencias, como antes Evitar confuso com os arquivos clientes e templates Contedo fora do ui:composition ser ignorado Mas a tag no topo top-level no arquivo de template ser <ui:composition>, no <html>
Cliente
<ui:composition xmlns="" xmlns:ui="" template="/templates/some-template.xhtml"> Usar ui:define com ui:include para por snippets
<ui:define name="section-name1-from-template-file"> <ui:include src="/snippets/some-snippet.xhtml"/> </ui:define> <ui:define name="section-name2-from-template-file"> Client-specific content </ui:define>
DOCTYPE; head, title, and body tags; style sheet; border em volta do cabealho
nico as paginas
texto corpo
Template (Top)
(/templates/eboats-template.xhtml)
<!DOCTYPE ...> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"> <h:head> <title><ui:insert name="title">Title</ui:insert></title> <link rel="stylesheet" type="text/css" href="./css/styles.css"/> </h:head> <h:body> <ui:insert name="header">Header</ui:insert> <p/>
Template
(/templates/eboats-template.xhtml)
<table border="5" align="center"> <tr><th class="title"> <ui:insert name="title">Title</ui:insert> </th></tr> </table> <p/> <table width="75" align="left" cellspacing="5"> <tr><td><ui:insert name="menu">Menu</ui:insert></td></tr> </table> <p/> <ui:insert name="body">Body</ui:insert> <br clear="all"/> <hr/> <ui:insert name="footer">Footer</ui:insert> </h:body></html>
Header File
(/snippets/header.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"> <table width="100%" class="dark"> <tr><th align="left"> <a href="welcome.jsf" class="white">Home</a>     <a href="products.jsf" class="white">Products</a>     <a href="services.jsf" class="white">Services</a>     <a href="contact.jsf" class="white">Contact Us</a> </th><th align="right"> <a href="cart.jsf" class="white">My Cart</a>     <a href="logout.jsf" class="white">Logout</a>     <a href="help.jsf" class="white">Help</a> </th></tr></table> </ui:composition>
Footer arquivo 1
(/snippets/footer-full.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"> <div align="center"> <a href="welcome.jsf">Home</a> | <a href="contact.jsf">Contact</a> | <a href="privacy.jsf">Privacy</a> </div> </ui:composition>
Este rodap incluido em quase todas as pginas que usam o templateeboats-template.xhtml. A pginas welcome usa um foote abreviado que no inclui a propria welcome.
Footer 2
(/snippets/footer-no-home.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"> <div align="center"> <a href="contact.jsf">Contact</a> | <a href="privacy.jsf">Privacy</a> </div> </ui:composition>
Objetivo
Ter varios buscadores de diferentes empresas(Google, Bing, Yahoo, etc.) Evitar repetir a caixa de busca loca e a maioria da formatao Fazer um template de busca geral Usar esse template para cada servio de busca Esse no um xhtml completo, no deve conterDOCTYPE, <html>, <head>, <body>, etc.
Soluo
(/templates/search-box-template.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"> <div align="center" > <table border="1"><tr bgcolor="black"><th> <font color="white">Search Site</font> </th></tr><tr><th> <form action="siteSearch"> <input type="text" name="query"/><br/> <input type="submit" value="Search"/> </form> </th></tr></table> Embora isso seja um template.
O arquivo cliente o usar como um snippet, ento a tag no nvel mais alto deve ser a <ui:composition>, e no <html>
(/snippets/google-search-box.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="/templates/search-box-template.xhtml"> <ui:define name="search-form"> <form action="http://google.com/search"> <input type="text" name="q"/><br/> <input type="submit" value="Google Search"/> </form> </ui:define> </ui:composition>
Este tambm um snippet que usa o layou criado anteriormente e ser usado em outro cliente
(/snippets/bing-search-box.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="/templates/search-box-template.xhtml"> <ui:define name="search-form"> <form action="http://bing.com/search"> <input type="text" name="q"/><br/> <input type="submit" value="Bing Search"/> </form> </ui:define> </ui:composition>
(/snippets/bing-search-box.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="/templates/search-box-template.xhtml"> <ui:define name="search-form"> <form action="http://search.yahoo.com/search"> <input type="text" name="p"/><br/> <input type="submit" value="Yahoo Search"/> </form> </ui:define> </ui:composition>
Cliente
(/welcome.xhtml)
<ui:define name="body"> <p/> <img src="./images/yacht.jpg" width="240" height="367" align="right" alt="Base-model yacht"/> Looking for a hole in the water into which to pour your money? You've come to the right place! We offer a wide selection of reasonably priced boats for everyday use. <h2>Yachts</h2> ... (more body content) </ui:define> <ui:define name="footer"> <ui:include src="/snippets/footer-no-home.xhtml"/> </ui:define> </ui:composition>
Cliente
Cliente
(/tankers.xhtml)
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="/templates/eboats-template.xhtml"> <ui:define name="title"> Eboats Oil Tankers! </ui:define> <ui:define name="header"> <ui:include src="/snippets/header.xhtml"/> </ui:define> <ui:define name="menu"> <ui:include src="/snippets/yahoo-search-box.xhtml"/> </ui:define>
Cliente 2
(/tankers.xhtml)
<ui:define name="body"> <img src="./images/yacht.jpg" alt="Yacht" align="right"/> <p/> Luxurious models for the <s>wasteful</s> wealthy buyer. <h2>Available Models</h2> Choose a model to see a picture along with price and availability information. ... (more body content) </ui:define> <ui:define name="footer"> <ui:include src="/snippets/footer-full.xhtml"/> </ui:define> </ui:composition>
Cliente 2
Cliente 3 e 4
Questo
Templates e snippets usados com URLs relativas Suponha arquivo cliente esteja em subdir/client.xhtml, acessado com http://host/context-root/subdir/client.jsf
Exemplo
Todas as URLs devem referenciar a subpasta <a href="welcome.jsf"> dever referenciar a http://host/context-root/subdir/welcome.jsf <img src="./images/yacht.jpg">imagens a http://host/context-root/subdir/images/yacht.jpg <link href="./css/styles.css"/> deve referenciar a http://host/context-root/subdir/css/styles.css
Hypertext links
Imagens
Style sheets
Soluo
Hypertext links
Ou <h:outputLink value="#{request.contextPath}/blah.jsf"/>
Images
Colocar as imagens em uma pasta chamada resources e usar <h:graphicImage name="blah.jpg" library="images"/>
Style sheets
Colocar a pasta de css na pasta resources e usar <h:outputStylesheet name="blah.css" library="css"/> Colocar os scripts dentro de resources and use <h:outputScript name="blah.js" library="scripts"/>
JavaScript
Aplicvel a:
Images Style sheets Regular hypertext links Qualquer TAG que use URL
Nunca somente <head> e <body> (ento jSF pode achar regies) f:ajax
Razes
Esta tag insere scripts automaticamente,e pode no achar o local de inserir quando no usado oh:head e h:body <h:outputStylesheet> no precisa ser no cabealhom ento JSF tem que ser capaz de localizar o cabealho para inserir o link que carrega o style sheet.
h:outputStylesheet
Usar #{request.contextPath}
Diferente de imagens, style sheets, e scripts, JSF no tem um jeito interno para lidar com links relativos Pode ser resolvido facilmente <a href="#{request.contextPath}/blah.jsf"> <h:outputLink value="#{request.contextPath}/blah.jsf"/>
Exemplos
Assume that your context root is /my-context. Then, both of the above build <a href="/my-context/blah.jsf">
JSF 2.0 adicionou o conceito de diretrios de recursos (resource folders). Cria um diretrio chamado resources, e cria subpastas dentro.
Em library, Pe o nome do diretorio de imagens Em name, passa o nome do arquivo sada <img src="/my-context/foo/bar.jgp"/>.
Exemplo
Exemplo
Sada <link type="text/css" rel="stylesheet" href="" /> onde href referencia aplicaao onde est a pagina /my-context/resources/css/blah.css
<a href="#{request.contextPath/somefile.jsf"/>
Result: yacht-client1.jsf
Result: yacht-client2.jsf
Perguntas?