<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gilliard Cordeiro &#187; JavaServer Faces</title>
	<atom:link href="http://blog.gilliard.eti.br/tag/javaserver-faces/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.gilliard.eti.br</link>
	<description>tá nervoso? vai programar!</description>
	<lastBuildDate>Wed, 21 Sep 2011 05:22:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Como trabalhar com ViewScope e Page</title>
		<link>http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/</link>
		<comments>http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 20:06:06 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[bookmarking]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[page-scope]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[view-scope]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=275</guid>
		<description><![CDATA[Uma coisa que não é muito intuitiva é a forma como o ViewScope do JSF e o scope Page do Seam funcionam. Como estamos acostumados com o escopo request, que termina quando a próxima view é renderizada, tendemos a pensar que esses escopos funcionam da mesma forma. Mas na verdade o escopo morre no momento [...]]]></description>
			<content:encoded><![CDATA[<p>Uma coisa que não é muito intuitiva é a forma como o <code><strong>ViewScope</strong></code> do JSF e o scope <code><strong>Page</strong></code> do Seam funcionam. Como estamos acostumados com o escopo request, que termina quando a próxima view é renderizada, tendemos a pensar que esses escopos funcionam da mesma forma. Mas na verdade o escopo morre no momento que uma nova view é setada. O problema é que depois que isso acontece ainda temos toda a fase 6 do jsf.</p>
<p>Para entendermos melhor o funcionamento, vamos considerar como exemplo uma tela de listagem de produtos (<code>produtoLista.xhtml</code>) onde selecionamos um produto e este é exibido em outra view, que mostra os detalhes desse produto (<code>produtoForm.xhtml</code>). Nessa aplicação vou usar o mesmo managed bean com <code><strong>@ViewScope</strong></code> para a listagem e para a tela do produto.</p>
<p>Usando o escopo <code><strong>view</strong></code>, quando clicamos num <code>h:command(Button | Link)</code> que tem dentro um <code>f:setPropertyActionListener</code> temos a impressão que o jsf não colocou o produto selecionado no <code>target</code>, no caso o <code><strong>produtoController.produto</strong></code>. Na verdade ele fez isso sim, mas assim que mudou da view de listagem para a de produto o <code>produtoController</code>, que continha o produto selecionado foi descartado. Então um novo <code>produtoController</code> é instanciado, e esse obviamente não conhece o produto selecionado. O funcionamento é simples, só não é intuitivo (vou fazer essa afirmação várias vezes que é pra ficar no subconsciente hehehe).</p>
<p>Na minha opinião, um bom comportamento padrão seria como o <a href="http://wiki.apache.org/myfaces/Extensions/CDI/DevDoc/Drafts/ViewConversationScoped" target="_blank">@ViewConversationScoped</a>. Mas como ninguém liga para a minha opinião, o jeito é usarmos os parâmetros de url para segurar esses valores. Pra variar já escrevi muito, então vamos ver na prática como fazer isso.</p>
<p>Na classe <code>Produto</code> vou simplesmente ignorar os getters e setters, <a href="http://groovy.codehaus.org/Groovy+Beans">Groovy like</a> =)</p>
<p>Entidade Produto</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@<span style="color: #003399; font-weight: bold;">Entity</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Produto <span style="color: #009900;">&#123;</span>
&nbsp;
	@Id @GeneratedValue
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">Integer</span> id<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">String</span> nome<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">String</span> descricao<span style="color: #339933;">;</span>
&nbsp;
        @<span style="color: #003399; font-weight: bold;">Override</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> toString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;Produto [descricao=&quot;</span> + descricao + <span style="color: #0000ff;">&quot;, id=&quot;</span> + id + <span style="color: #0000ff;">&quot;, nome=&quot;</span> + nome + <span style="color: #0000ff;">&quot;]&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O Controlador</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@ManagedBean
@ViewScope
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ProdutoController <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Produto produto<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399; font-weight: bold;">List</span><span style="color: #339933;">&lt;</span>Produto<span style="color: #339933;">&gt;</span> produtos<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//método init serve só para vermos em que momento o bean é destruído</span>
	@PostConstruct
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.init()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		atribuirEstadoInicial<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * Deixa o bean em um estado inicial válido tanto para edição quanto para listagens
	 */</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #006600; font-weight: bold;">void</span> atribuirEstadoInicial<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.atribuirEstadoInicial()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">//serve para deixar o bean em um estado onde pode acontecer uma nova edição</span>
		produto = <span style="color: #000000; font-weight: bold;">new</span> Produto<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #666666; font-style: italic;">//limpa a listagem previamente carregada pois ela não contém um elemento novo ou contém um recém excluído</span>
		produtos = <span style="color: #006600; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> salvar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.salvar()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">begin</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">merge</span><span style="color: #009900;">&#40;</span>produto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">commit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		atribuirEstadoInicial<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Produto getProduto<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> produto<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setProduto<span style="color: #009900;">&#40;</span>Produto produto<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoController.setProduto(): &quot;</span> + produto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">produto</span> = produto<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@<span style="color: #003399; font-weight: bold;">SuppressWarnings</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">List</span><span style="color: #339933;">&lt;</span>Produto<span style="color: #339933;">&gt;</span> getProdutos<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000;  font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>produtos == <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			produtos = JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">createQuery</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;select p from Produto p&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResultList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> produtos<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> setProdutos<span style="color: #009900;">&#40;</span><span style="color: #003399; font-weight: bold;">List</span><span style="color: #339933;">&lt;</span>Produto<span style="color: #339933;">&gt;</span> produtos<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">produtos</span> = produtos<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E o converter</p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@FacesConverter<span style="color: #009900;">&#40;</span>forClass=Produto.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ProdutoConverter <span style="color: #000000; font-weight: bold;">implements</span> Converter <span style="color: #009900;">&#123;</span>
&nbsp;
	@<span style="color: #003399; font-weight: bold;">Override</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">Object</span> getAsObject<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399; font-weight: bold;">String</span> string<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoConverter.getAsObject(): &quot;</span> + string<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000;  font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>string == <span style="color: #006600; font-weight: bold;">null</span> || string.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #006600; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> JpaUtil.<span style="color: #006633;">getEntityManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span>Produto.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #003399; font-weight: bold;">Integer</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@<span style="color: #003399; font-weight: bold;">Override</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399; font-weight: bold;">String</span> getAsString<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399; font-weight: bold;">Object</span> object<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		Produto produto = <span style="color: #009900;">&#40;</span>Produto<span style="color: #009900;">&#41;</span> object<span style="color: #339933;">;</span>
		<span style="color: #003399; font-weight: bold;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ProdutoConverter.getAsString(): &quot;</span> + produto<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000;  font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>produto == <span style="color: #006600; font-weight: bold;">null</span> || produto.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> == <span style="color: #006600; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #006600; font-weight: bold;">null</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399; font-weight: bold;">String</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span>produto.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Na verdade, até aqui não tem muita novidade. No resto também não vai ter novidade <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  mas vamos lá.</p>
<p>A listagem de produtos:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:dataTable</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produtos}&quot;</span> <span style="color: #000066;">var</span>=<span style="color: #ff0000;">&quot;produto&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>ID<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		#{produto.id}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Nome<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		#{produto.nome}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Descrição<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		#{produto.descricao}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Ações<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:link</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;editar 1&quot;</span> <span style="color: #000066;">outcome</span>=<span style="color: #ff0000;">&quot;produtoForm&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;id&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produto.id}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:link<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandLink</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;editar 2&quot;</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;produtoForm?faces-redirect=true&amp;amp;includeViewParams=true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:setPropertyActionListener</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produto}&quot;</span> <span style="color: #000066;">target</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandLink<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:dataTable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>E o form de produto:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:viewParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;id&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Detalhes do Produto<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGrid</span> <span style="color: #000066;">columns</span>=<span style="color: #ff0000;">&quot;2&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
				Nome: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:inputText</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto.nome}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
				Descrição: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:inputText</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{produtoController.produto.descricao}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{produtoController.salvar}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Salvar&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGrid<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>Por fim, vamos analisar o log do click nos links &#8220;editar 1&#8243; e &#8220;editar 2&#8243;</p>
<p>link &#8220;editar 1&#8243;</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">ProdutoController.init()
ProdutoController.atribuirEstadoInicial()
ProdutoConverter.getAsObject(): 1
ProdutoController.setProduto(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoConverter.getAsString(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]</pre></div></div>

<p>link &#8220;editar 2&#8243;</p>

<div class="wp_syntax"><div class="code"><pre class="console" style="font-family:monospace;">ProdutoController.setProduto(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoConverter.getAsString(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoController.init()
ProdutoController.atribuirEstadoInicial()
ProdutoConverter.getAsObject(): 1
ProdutoController.setProduto(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]
ProdutoConverter.getAsString(): Produto [descricao=Fermento em Pó, id=1, nome=Fermento]</pre></div></div>

<p><br/><br/><br />
Beleza, agora sim tem código pra caramba&#8230; boa parte dele aliás bem parecido com o <a href="http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/">desse post</a>. No meio disso tudo o que temos que prestar atenção é nos dois botões editar da produtoLista.xhtml. O link <strong>&#8220;editar 1&#8243;</strong> é exatamente igual ao apresentado no post que acabei de citar. O valor é passado por GET e o converter do viewParam faz o trabalho de nos deixar trabalhar sempre OO.</p>
<p>Agora vamos ver o link <strong>&#8220;editar 2&#8243;</strong>. Nesse exemplo a gente tem um post para uma view que usa um ManagedBean com escopo <code><strong>@ViewScope</strong></code> para uma outra view cujo MB é o mesmo, mas isso é um detalhe. </p>
<p>Na primeira linha temos o <code><strong>f:setPropertyActionListener</strong></code> trabalhando e chamando o set da propriedade, e na segunda linha vimos o converter gerando o texto (nesse caso id) que irá representar esse objeto na url da próxima view, pois deixamos o <code><strong>includeViewParams=true</strong></code>. Note que em momento algum passamos a propriedade que vai representar o produto na url como fizemos no <strong>&#8220;editar 1&#8243;</strong>. Quem vai fazer isso é o conversor. </p>
<p>Depois, entre as linhas 2 e 3 a view é trocada e o MB é perdido, mas como a url agora já tem o valor a ser mantido, fica igual o exemplo anterior. A única coisa que pode parecer é que teremos buscas desnecessárias ao banco. Mas como você vai estar usando algo mais esperto do que buscar no braço, a JPA já vai estar com esse objeto no cache de primeiro nível &#8211; pois estou usando o padrão <code><a href="http://community.jboss.org/wiki/OpenSessioninView">OpenEntityManagerInView</a></code> &#8211; e não haverá nenhum overhead por causa dessa outra forma de fazer. E isso é muito importante, apesar de termos um converter no meio, e do POST em vez de GET rodar o restore view do jsf, o objeto selecionado não será em momento algum trazido mais de uma vez no banco pois o <code><strong>EntityManager</strong></code> está com ele no cache (para isso não precisa de configuração nenhuma). Como estamos com o bean em escopo view, também não será buscado novamente a lista do banco. Então a única perda real nesse caso é não termos a url montada já na tela de listagem &#8211; o que pode nem ser uma perda. De fato todo o &#8220;overhead&#8221; dessa abordagem resume-se a chamadas de métodos locais como getters. Então provavelmente se sua aplicação ficar lenta aqui, o problema é outro.</p>
<p>Novamente o que incomoda é a falta de intuitividade dessa abordagem. Mas o funcionamento é simples. Só temos que lembrar que nessa abordagem do <strong>&#8220;editar 2&#8243;</strong> só vai funcionar se tivermos o <code><strong>includeViewParams</strong></code> ativo, seja no link ou na regra de navegação do <code><strong>faces-config.xml</strong></code>. Sem isso o JSF não se preocupa em incluir na próxima view os parâmetros de url.</p>
<p><br/><br/></p>
<h3>
Importante! (update)<br />
</h3>
<p><br/><br/></p>
<p>Apesar da abordagem do link <strong>&#8220;editar 1&#8243;</strong>, que usa GET ser a forma mais bacana de se trabalhar, e inclusive é a &#8220;novidade&#8221; do JSF 2, a abordagem do <strong>&#8220;editar 2&#8243;</strong> tem se mostrado mais segura. Isso porque até a versão atual do JSF (2.1) a remoção do bean no escopo view não ocorre da forma esperada quando usamos GET para sair da página, porém quando usamos POST (jeitão que o JSF já está bem acostumado) a coisa rola corretamente.</p>
<p>Agora caso você queria usar um escopo que dure mais que uma página como <a href="http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/#comment-17878">comentado pelo Rodrigo</a> a melhor solução na minha opinião é usar conversação. Solução que inclusive permite trocar de páginas usando GET sem o problema do escopo <code>view</code>, que desse modo não remove o bean, pois na conversação, se você não matar, o timeout mata.<br />
Uma forma simples de usar é iniciar a conversação quando abrimos a view. Para isso podemos fazer de <a href="http://stackoverflow.com/questions/6161618/postconstruct-called-multiple-time-for-conversationscoped-bean">várias formas</a>, mas a mais simples é usando o <a href="http://seamframework.org/Seam3/FacesModule">seam-faces</a>:</p>
<p><strong>Código da view</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">&nbsp;
<span style="color: #339933;">&lt;</span>f:metadata<span style="color: #339933;">&gt;</span>
   <span style="color: #339933;">&lt;</span>s:viewAction action=<span style="color: #0000ff;">&quot;#{meuBean.init}&quot;</span> <span style="color: #000000;  font-weight: bold;">if</span>=<span style="color: #0000ff;">&quot;#{conversation.transient}&quot;</span> /<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>/f:metadata<span style="color: #339933;">&gt;</span></pre></div></div>

<p><strong>Código do Bean</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@Named
@ConversationScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MeuBean<span style="color: #009900;">&#123;</span>
    @Begin 
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ou</p>
<p><strong>Código do Bean (alternativo)</strong></p>

<div class="wp_syntax"><div class="code"><pre class="java5" style="font-family:monospace;">@Named
@ConversationScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MeuBean<span style="color: #009900;">&#123;</span>
&nbsp;
    @In
    Conversation conversation
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #006600; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        conversation.<span style="color: #006633;">begin</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Mas não estou dizendo para criar conversação e largar, tem que matar ela. Só estou falando que se for pra largar pra trás (coisa feia <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> ) é melhor fazer com conversação do que com view ou session.</p>
<p>E ainda outra forma de usar um escopo view em mais de uma página é usar o <a href="https://cwiki.apache.org/confluence/display/EXTCDI/JSF+Usage#JSFUsage-ViewAccessScope">@ViewAccessScope</a> do apache CODI (<a href="http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/#comment-13202">citado</a> também pelo João). Ele funciona como o &#8220;bom e velho&#8221; <a href="http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/a4j_keepAlive.html">Keep Alive</a> (anotação ao tag), e em vez de matar o bean na troca de página, ele espera o fim do response, e se o bem não for usado, aí sim é removido. O única problema é que a configuração do apache CODI, principalmente quando já estamos rodando o seam-faces, é um pouquinho mais charope. Mas funciona.</p>
<p><br/><br/></p>
<h3>
Concluindo&#8230;<br />
</h3>
<p><br/><br/></p>
<p>Nada do que mostrei aqui é novo ou difícil. Mas resolvi escrever pois em uma semana tive três dúvidas iguais aqui no blog sobre esse assunto. E nos cursos de Seam (escopo Page) e JSF 2 que ministro vejo que esse assunto demora para ser digerido também. Então espero que esse post tenha sido útil para minimizar essas dúvidas. Usar esse recurso do JSF 2 (ou Seam) é simples, mas se te incomodar muito, ou se você quiser usar uma conversação em uma única view (<code><strong>@ViewScope</strong></code> não segura o <code><strong>EntityManager</strong></code> aberto e com isso não evita <code><strong>LazyinitializationException</strong></code>), lembre-se que JEE6 define extensões portáveis. Então uma boa coisa é procurar coisas como o escopo que eu citei no início do post.</p>
<p>Sei que o pessoal do Java é meio purista, as vezes torce o nariz para o que não é especificado, mas se ganha muito procurando a solução para o seu problema em um projeto opensource bacana em vez de passar raiva e esperar até sair a próxima versão de alguma especificação, o que obviamente vai demorar mais do que uma novidade nascida direto da comunidade (apache, jboss.org, etc). Mas isso é assunto para um próximo post.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2010/11/como-trabalhar-com-viewscope-e-page/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Mojarra (JSF RI) 2.0 disponível</title>
		<link>http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/</link>
		<comments>http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 18:47:31 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/</guid>
		<description><![CDATA[Depois de uma boa espera, está disponível a versão final do JSF 2.0. Nos demais post deste blog você pode ver alguns exemplos de novas funcionalidades e baixar projetos com JSF 2 (não a versão final) rodando. Como faz algum tempo que eu venho postando sobre isso, alguns exemplos podem ter pequenas diferenças do que [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de uma boa espera, está disponível a versão final do <a href="https://javaserverfaces.dev.java.net/servlets/ProjectDocumentList?folderID=11852">JSF 2.0</a>.</p>
<p>Nos <a href="http://blog.gilliard.eti.br/category/jsf/">demais post</a> deste blog você pode ver alguns exemplos de novas funcionalidades e baixar projetos com JSF 2 (não a versão final) rodando.</p>
<p>Como faz algum tempo que eu venho postando sobre isso, alguns exemplos podem ter pequenas diferenças do que está agora na versão final, mas nada que prejudique o entendimento, pois apesar da implementação estar saindo agora, a especificação já está pronta há algum tempo.</p>
<p>Tem vários assuntos que não tive tempo de escrever um post, mas hoje em dia já não está difícil encontrar exemplos de JSF 2 na internet.</p>
<p>Outros links:</p>
<p><a href="https://javaserverfaces.dev.java.net/">https://javaserverfaces.dev.java.net/</a><br />
<a href="https://javaserverfaces.dev.java.net/nonav/rlnotes/2.0.0/index.html">https://javaserverfaces.dev.java.net/nonav/rlnotes/2.0.0/index.html</a><br />
<a href="https://javaserverfaces.dev.java.net/maven2">https://javaserverfaces.dev.java.net/maven2</a></p>
<p>Boa diversão <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/10/mojarra-jsf-ri-2-0-disponivel/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>URLs amigáveis no JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/#comments</comments>
		<pubDate>Thu, 28 May 2009 03:36:19 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[bookmarking]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=163</guid>
		<description><![CDATA[Hoje vou falar de mais uma novidade do JSF 2, cuja falta era motivo de muita reclamação: URLs amigávies, bookmarking, método GET e outros nomes que podemos dar. O suporte a essa nova funcionalidade é dado por dois pares de componentes, de um lado h:button e h:link e do outro f:metadata e f:viewParam. Os componentes [...]]]></description>
			<content:encoded><![CDATA[<p>Hoje vou falar de mais uma novidade do JSF 2, cuja falta era motivo de muita reclamação: URLs amigávies, bookmarking, método GET e outros nomes que podemos dar. O suporte a essa nova funcionalidade é dado por dois pares de componentes, de um lado h:button e h:link e do outro f:metadata e f:viewParam.</p>
<p>Os componentes h:button e h:link servem para originar as ações jsf assim como os componentes h:command{Button|Link}, porém usando GET em vez de POST. Esses componentes possuem um atributo chamado <strong>outcome</strong>, que representa a regra de navegação do JSF, assim como seria colocar uma String diretamente na action do h:command{Button|Link}. Para passar parâmetros colocamos a tag f:param dentro do h:link ou h:button.</p>
<p>Como exemplo vamos ver uma aplicaçãozinha que tem uma tela de listagem e outra de visualização de Pessoas. A seguir um trecho da página de listagem de pessoas, <strong>listarPessoas.xhtml</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:dataTable</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{pessoaController.pessoas}&quot;</span> <span style="color: #000066;">var</span>=<span style="color: #ff0000;">&quot;pessoa&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			#{pessoa.nome}
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:link</span> <span style="color: #000066;">outcome</span>=<span style="color: #ff0000;">&quot;/verPessoa&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Editar&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
				<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;pessoa&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{pessoa.nome}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:link<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:column<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:dataTable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Nesse exemplo, no outcome eu já estou usando o esquema novo de navegação comentado no <a href="http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/">post passado</a>. O link acima vai gerar uma url parecida com <strong><em>http://localhost:8080/exemplojsf2/verPessoa.jsf?pessoa=fulano_0</em></strong>.</p>
<p>Agora do lado da página que recebe a requisição temos os componentes f:metadata e f:viewParam. A primeira é apenas uma tag que engloba as f:viewParam. Já as tags f:viewParam se comportam de forma muito parecida com um h:inputText, podemos dizer que praticamente a única diferença é no input a gente digita em um formulário, enquanto na f:viewParam escrevemos na URL.</p>
<p>A tag f:viewParam possue os seguintes atributos: converter, converterMessage, required, requiredMessage, validator, validatorMessage, value, valueChangeListener, maxlength e for (este último voltado para o novo esquema de component composition do Facelets). Como podemos ver, é praticamente um h:inputText.</p>
<p>Vamos ver então um trecho do código da página que recebe a requisição, <strong>verPessoa.xhtml</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	    	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:viewParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;pessoa&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{pessoaController.pessoaSelecionada}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:metadata<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Ver Pessoa<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		Nome: #{pessoaController.pessoaSelecionada.nome}
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:view<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Não precisei colocar um converter no f:viewParam pois configurei um converter &#8220;<strong>forClass</strong>&#8221; como veremos mais a frente.</p>
<p>Agora a nossa classe</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Pessoa <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> nome<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> nome<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">nome</span> <span style="color: #339933;">=</span> nome<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getter e setter suprimido</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Isso mesmo, a classe é complexa desse jeito  <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Como o intuito é só um exemplo, eu nem me preocupei com banco de dados ou algum mecanismo mais interessante, apenas criei um conversor para mostrar que o novo esquema não permite apenas o uso de Strings. Segue o código do conversor:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@FacesConverter<span style="color: #009900;">&#40;</span>forClass<span style="color: #339933;">=</span>Pessoa.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PessoaConverter <span style="color: #000000; font-weight: bold;">implements</span> Converter <span style="color: #009900;">&#123;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getAsObject<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399;">String</span> string<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span>string<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getAsString<span style="color: #009900;">&#40;</span>FacesContext context, UIComponent component, <span style="color: #003399;">Object</span> object<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>Pessoa<span style="color: #009900;">&#41;</span>object<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getNome</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E agora nosso managed bean que recebe não uma String, e sim objetos do nosso domínio. Eu falo isso o tempo todo pois preciso deixar isso bem claro, senão eu fico doido de ver uma aplicação usando JSF passando String e Integer de um lado pro outro <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>Mas tudo bem, deixando o desabafo pra lá vamos ao código:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;pessoaController&quot;</span><span style="color: #009900;">&#41;</span>
@RequestScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PessoaController <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Pessoa pessoaSelecionada<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>pessoa<span style="color: #339933;">&gt;</span> pessoas<span style="color: #339933;">;</span>
&nbsp;
	@PostConstruct
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		pessoas <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>pessoa<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			pessoas.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fulano_&quot;</span> <span style="color: #339933;">+</span> i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getters e setters suprimidos</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Acredito que por hoje seja suficiente. Vou ver se em breve escrevo algo mais específico sobre facelets.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/urls-amigaveis-no-jsf-2/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>implicit navigation do JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/#comments</comments>
		<pubDate>Tue, 19 May 2009 01:32:24 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=138</guid>
		<description><![CDATA[O JSF 2 teve o mecanismo de navegação melhorado. Agora além de regras de navegação implícitas foi adicionado um teste que pode ser feito usando a tag &#60;if&#62; dentro do &#60;navigation-case&#62;. E para finalizar a tag &#60;to-view-id&#62; aceita EL, o que torna tudo mais dinâmico. Mas como são várias coisas, vamos por partes Implicit Navigation [...]]]></description>
			<content:encoded><![CDATA[<p>O JSF 2 teve o mecanismo de navegação melhorado. Agora além de regras de navegação implícitas foi adicionado um teste que pode ser feito usando a tag &lt;if&gt; dentro do &lt;navigation-case&gt;. E para finalizar a tag &lt;to-view-id&gt; aceita EL, o que torna tudo mais dinâmico.</p>
<p>Mas como são várias coisas, vamos por partes</p>
<h2>Implicit Navigation</h2>
<p>Agora quando retornamos um outcome na nossa action, caso nenhuma regra de navegação compatível seja encontrada, a navegação implícita entra em cena.</p>
<p>Vamos considerar os seguintes dados</p>
<table border="1">
<tr>
<th>from-view-id</th>
<th>outcome</th>
<th>to-view-id implícita</th>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>view2</td>
<td>/pasta1/view2.xhtml</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>/view2</td>
<td>/view2.xhtml</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>/pasta2/view3</td>
<td>/pasta2/view3.xhtml</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>view2.groovy</td>
<td>/pasta1/view2.groovy</td>
</tr>
<tr>
<td>/pasta1/view1.xhtml</td>
<td>/outrapasta/view2.groovy</td>
<td>/outrapasta/view2.groovy</td>
</tr>
</table>
<p><br/><br />
Acredito que a tabela seja auto explicativa, mas só para consolidar: caso o outcome devolvido comece com &#8220;/&#8221; será considerado como caminho absoluto, senão a view será procurada na mesma pasta da view que originou a action. Além disso se nenhuma extensão de arquivo for informada, será considerada a mesma extensão da view que originou a action.</p>
<p>E por fim, podemos definir o atributo &#8220;<strong>faces-redirect=true</strong>&#8221; para informar que queremos que seja usado um redirect, assim como faríamos com <redirect/> se tivéssemos definido nossa regra de navegação via xml, como por exemplo &#8220;<strong>meuOutcome?faces-redirect=true</strong>&#8220;.</p>
<h2>Navigation case com &lt;if&gt;</h2>
<p>Assim como as implicit navigation, o Seam também tem o &lt;if&gt; como o do JSF 2, porém no Seam esse &lt;if&gt; fica no pages.xml, um arquivo do Seam. Como sempre, vamos ver um exemplo para facilitar o entendimento.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;pessoaBean&quot;</span><span style="color: #009900;">&#41;</span>
@RequestScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> PessoaBean<span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> EntityManager em<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//injetado por algum mecanismo</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Pessoa pessoa <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Pessoa<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> actionSalvar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		em.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>pessoa<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getters e setters suprimidos</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>agora vamos ver o faces-config.xml</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/cadastroPessoa.xhtml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;if<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>#{pessoaBean.pessoa.id != null}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/if<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/listagemPessoas.xhtml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>No nosso exemplo acima, mesmo sem retornar nenhum outcome, a navegação acontece da view &#8220;<strong>/cadastroPessoa.xhtml</strong>&#8221; para a view &#8220;<strong>/listagemPessoas.xhtml</strong>&#8220;, graças ao &lt;if&gt; do nosso &lt;navigation-case&gt;. Na expressão do exemplo usei algo bem simples, considerei que se o id da pessoa está diferente de nulo é porque a ação de salvar foi executada com sucesso. Obviamente podemos evoluir esse exemplo, mas como a finalidade aqui é didática acredito que seja sufucuente como está.</p>
<h2>EL no &lt;to-view-id&gt;</h2>
<p>Para finalizar vamos dar uma olhada no exemplo do uso da EL no &lt;to-view-id&gt;. Vamos ver esse outro exemplo.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;cidadeBean&quot;</span><span style="color: #009900;">&#41;</span>
@RequestScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CidadeBean<span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> EntityManager em<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//injetado por algum mecanismo</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Cidade cidade <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cidade<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> nextView<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> actionSalvar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		em.<span style="color: #006633;">persist</span><span style="color: #009900;">&#40;</span>cidade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		nextView <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;/listagemCidades.xhtml&quot;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;sucesso&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//getters e setters suprimidos</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>E no faces-config.xml temos o seguinte</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/cadastroCidade.xhtml<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/from-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;from-outcome<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>sucesso<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/from-outcome<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>#{cidadeBean.nextView}<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;to-view-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-case<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/navigation-rule<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
...</pre></div></div>

<p>Com isso fechamos a parte de NavigationHandler do JSF 2. Na verdade ainda tem como novidade a possibilidade de consultarmos os NavigationCase&#8217;s de forma programática. Mas isso eu comento melhor quando for falar do que podemos fazer de forma programática no JSF 2 usando a implementação de referência, Mojarra (pois essas configurações programáticas que irei comentar não são especificadas).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/implicit-navigation-jsf-2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Conversation Scope usando @CustomScoped do JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/#comments</comments>
		<pubDate>Tue, 12 May 2009 15:28:25 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=131</guid>
		<description><![CDATA[Apesar do título, o JSF 2 não vai ter um escopo Conversation ou coisa parecida como tem no Seam ou Orchestra. O que vai ter é o suporte direto a escopos personalizados, o que torna simples a criação de um escopo como Conversation. Nesse exemplo eu desenvolvi um escopo de conversação simples, mas não é [...]]]></description>
			<content:encoded><![CDATA[<p>Apesar do título, o JSF 2 não vai ter um escopo Conversation ou coisa parecida como tem no Seam ou Orchestra. O que vai ter é o suporte direto a escopos personalizados, o que torna simples a criação de um escopo como Conversation.</p>
<p>Nesse exemplo eu desenvolvi um escopo de conversação simples, mas não é difícil melhorá-lo para suportar diversas conversações simultâneas, assimilando a idéia a gente vê que não é nenhum bicho de sete cabeças. Claro que o principal objetivo é o aprendizado de como tudo funciona, e não ficar implementando o que já tem pronto em diversos frameworks.</p>
<p>Vamos então ao exemplo.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;testeBean&quot;</span><span style="color: #009900;">&#41;</span>
@CustomScoped<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#{conversacao}&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TesteBean <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Integer</span> contador<span style="color: #339933;">;</span>
&nbsp;
	@PostConstruct
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;TesteBean.init()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		contador <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> incrementarContador<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		contador<span style="color: #339933;">++;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> iniciaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">iniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> finalizaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">finalizar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> getContador<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">return</span> contador<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setContador<span style="color: #009900;">&#40;</span><span style="color: #003399;">Integer</span> contador<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">contador</span> <span style="color: #339933;">=</span> contador<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Acima está um managed bean que chamei de &#8220;beanTeste&#8221;. Coloquei um <em>println</em> no método <strong>init()</strong> e anotei esse método com <strong>@PostConstruct</strong>. Na prática isso quer dizer que toda vez que o managed bean for construído esse método será chamado, e consequentemente aparecerá no console. Isso é útil para vermos que o escopo de conversação realmente está funcionando. Já que estamos falando de escopo personalizado, quem faz isso é a anotação <strong>@CustomScoped</strong>, que recebe como valor uma EL que será resolvida por um EL Resolver que vamos criar.</p>
<p>Agora vamos ver a tela</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">Contador atualizado via ajax e mantido com a conversação: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;output3&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{testeBean.contador}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;br</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{testeBean.incrementarContador}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Incrementar Contador&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;output3&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{testeBean.iniciarConversacao}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Iniciar Conversação&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;@none&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{testeBean.finalizarConversacao}&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Finalizar Conversação&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;@none&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Tanto o exemplo da tela quanto do managed bean estão simplificados para o nosso exemplo, mas a versão disponível para download contém uns exemplos para testarmos o funcionamento do ajax também.</p>
<p>A idéia do nosso escopo &#8220;conversacao&#8221; é o mesmo do Seam, ele funciona como request até que seja explicitamente iniciada a conversação. Quando isso ocorre, o escopo passa a ser statefull até que a conversação seja finalizada, fazendo com que ela funcione como request novamente.</p>
<p>Seguindo essa idéia, o contador que aparece na tela não vai sair de &#8220;1&#8243; até que a conversação seja iniciada, pois como o escopo é request, toda vez que executamos a ação &#8220;incrementaContador&#8221; o managed bean será criado novamente (contador = 0), depois a ação será executada (contador = 1) e então a página será renderizada (exibe contador = 1). Agora se a conversação for iniciada o managed bean será mantido entre as requisições, e o contador não será zerado até que a conversação termine.</p>
<p>Para nosso escopo funcionar, precisamos de um <strong>ELResolver</strong>, que será quem vai conseguir dizer para o faces de onde virá os objetos relacionados ao escopo &#8220;conversacao&#8221;. Registramos nosso ELResolver no faces-config.xml assim</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">'1.0'</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">'UTF-8'</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;faces-config</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">xsi:schemaLocation</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd&quot;</span></span>
<span style="color: #009900;">              <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;2.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;application<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;el-resolver<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>br.eti.gilliard.exemplojsf2.conversacao.ConversacaoELResolver<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/el-resolver<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/application<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/faces-config<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>E a implementação fica assim</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ConversacaoELResolver <span style="color: #000000; font-weight: bold;">extends</span> ELResolver <span style="color: #009900;">&#123;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getValue<span style="color: #009900;">&#40;</span>ELContext elContext, <span style="color: #003399;">Object</span> base, <span style="color: #003399;">Object</span> property<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>property <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> PropertyNotFoundException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;A Propriedade não pode ser nula!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>base <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
			<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>Conversacao.<span style="color: #006633;">NOME_ESCOPO</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>property.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
			<span style="color: #009900;">&#123;</span>
				Conversacao conversacao <span style="color: #339933;">=</span> Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				elContext.<span style="color: #006633;">setPropertyResolved</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000000; font-weight: bold;">return</span> conversacao<span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
&nbsp;
			Conversacao conversacao <span style="color: #339933;">=</span> Conversacao.<span style="color: #006633;">instancia</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">return</span> getValue<span style="color: #009900;">&#40;</span>conversacao, property.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, elContext<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>base <span style="color: #000000; font-weight: bold;">instanceof</span> Conversacao<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> getValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>Conversacao<span style="color: #009900;">&#41;</span> base, property.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, elContext<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> getValue<span style="color: #009900;">&#40;</span>Conversacao conversacao, <span style="color: #003399;">String</span> property, ELContext elContext<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">Object</span> objeto <span style="color: #339933;">=</span> conversacao.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>property<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		elContext.<span style="color: #006633;">setPropertyResolved</span><span style="color: #009900;">&#40;</span>objeto <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">return</span> objeto<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// os outros métodos foram suprimidos nesse exemplo</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Essa é uma implementação comum de EL Resolver, onde eu uso o objeto retornado por Conversacao.instancia() para localizar as propriedades solicitadas.</p>
<p>Para o jsf um escopo nada mais é do que um <strong>java.util.Map</strong>, e de fato a classe Conversacao estende <strong>ConcurrentHashMap</strong>, ou seja, é um Map como pede o jsf. Fora isso os métodos get e put foram sobrescritos para funcionarem de acordo com nossa especificação de conversação, ou seja, se ela não foi iniciada tudo deve funcionar como request, agora quando a conversação é iniciada, os valores passam a ser guardados dentro da sessão do usuário, fazendo assim ficar statefull. Depois que a conversação é finalizada os valores voltam a ser guardados no request.</p>
<p>Antes de ver a implementação da classe <strong>Conversacao</strong>, o mais importante é entender como o mecanismo de resolução de EL funciona. Como visto no faces-config.xml, não existe nenhuma ligação da nossa implementação de <strong>ELResolver</strong> com a El &#8220;#{conversacao}&#8221; que colocamos na anotação <strong>@CustomScoped</strong> do nosso managed bean. Toda vez que uma EL é encontrada ela é passada para os ELResolvers contidos na aplicação. Obviamente existem outras implementações padrões já disponíveis, e a nossa vai entrar nessa fila. Como nenhuma das outras implementações vai saber resolver essa EL, ela acaba vindo para a nossa implementação, e então quando encontramos o objeto procurado utilizamos o método &#8220;<strong>ElContext.setPropertyResolved(boolean b)</strong>&#8221; passando <strong>true</strong> para informar que não precisa continuar perguntando para os demais <strong>ELResolver</strong>&#8216;s, pois o nosso já descobriu quem é o objeto.</p>
<p>Existem alguns detalhes que devemos seguir ao implementar um escopo personalizado, como o de avisar, utilizando o novo sistema de eventos do JSF 2, que estamos criando ou destruindo nosso escopo.</p>
<p>Além disso para fazer essa implementação suportar múltiplas conversações seria necessário apenas colocar um nível a mais de mapa na nossa implementação, onde teríamos uma identificação da conversação e então seu contexto. Em vez de um simples Map, ficaria um Map de Map <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  . Então para saber qual Map interno devolver a gente buscaria a conversação atual de algum contexto da nossa escolha, e poderíamos deixar um combobox sempre visível na tela para o usuária escolher a conversação que ele quer usar. Novamente nada de novo, tudo igual o funcionamento do Seam, por exemplo.</p>
<p>Agora sim vamos à implementação da classe <strong>Conversacao</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Conversacao <span style="color: #000000; font-weight: bold;">extends</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>string,Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">long</span> serialVersionUID <span style="color: #339933;">=</span> 7556965369432050706L<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> NOME_ESCOPO <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;conversacao&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> CONVERSACAO_ATUAL <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;exemplojsf2.conversacao.ConversacaoAtual&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> conversacaoNaoIniciada <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> Conversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Conversacao instancia<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> sessionMap <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSessionMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Conversacao conversacao <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Conversacao<span style="color: #009900;">&#41;</span> sessionMap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>conversacao <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			conversacao <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Conversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			sessionMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL, conversacao<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> conversacao<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> get<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> propriedade<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//se a conversacao nao for iniciada funciona como request</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>conversacaoNaoIniciada<span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> pegarDoRequest<span style="color: #009900;">&#40;</span>propriedade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>propriedade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> pegarDoRequest<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> propriedade<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>requestConversation <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> requestConversation.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>propriedade<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> put<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> key, <span style="color: #003399;">Object</span> value<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">//se a conversacao nao for iniciada funciona como request</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>conversacaoNaoIniciada<span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">return</span> colocarNoRequest<span style="color: #009900;">&#40;</span>key, value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>key, value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> colocarNoRequest<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> key, <span style="color: #003399;">Object</span> value<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
&nbsp;
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestMap <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> requestMap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>requestConversation <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			requestConversation <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			requestMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL, requestConversation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">return</span> requestConversation.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>key, value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000000; font-weight: bold;">return</span> requestConversation.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>key, value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> iniciar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		conversacaoNaoIniciada <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		promoverRequestParaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		notificarCriacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> promoverRequestParaConversacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">putAll</span><span style="color: #009900;">&#40;</span>requestConversation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> notificarCriacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		ScopeContext context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ScopeContext<span style="color: #009900;">&#40;</span>NOME_ESCOPO, <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		FacesContext facesContext <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		facesContext.<span style="color: #006633;">getApplication</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">publishEvent</span><span style="color: #009900;">&#40;</span>facesContext, PostConstructCustomScopeEvent.<span style="color: #000000; font-weight: bold;">class</span>, context<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> finalizar<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		notificarFinalizacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		conversacaoNaoIniciada <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
		rebaixarConversacaoParaRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span>
&nbsp;
	@SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> rebaixarConversacaoParaRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestMap <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getRequestMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span> requestConversation <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> requestMap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>requestConversation <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			requestConversation <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConcurrentHashMap<span style="color: #339933;">&lt;</span>string, Object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			requestMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL, requestConversation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		requestConversation.<span style="color: #006633;">putAll</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getExternalContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getSessionMap</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">remove</span><span style="color: #009900;">&#40;</span>CONVERSACAO_ATUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> notificarFinalizacao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		ScopeContext context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ScopeContext<span style="color: #009900;">&#40;</span>NOME_ESCOPO, <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		FacesContext facesContext <span style="color: #339933;">=</span> FacesContext.<span style="color: #006633;">getCurrentInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		facesContext.<span style="color: #006633;">getApplication</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">publishEvent</span><span style="color: #009900;">&#40;</span>facesContext, PreDestroyCustomScopeEvent.<span style="color: #000000; font-weight: bold;">class</span>, context<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O download do exemplo pode ser feito <a href="http://blog.gilliard.eti.br/arquivos/exemplo-conversacao-jsf2.war">aqui</a>.</p>
<p>Com certeza deve ter algum errinho nessa implementação, mas se tiver não se desespere, por essas e outras que você certamente deve estar usando um framework mais confiável na tua aplicação do que uma implementação de &#8220;fundo de quintal&#8221; <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  . De qualquer forma encontrando os errinhos me diga que eu vou corrigindo.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>f:ajax no JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/#comments</comments>
		<pubDate>Mon, 11 May 2009 13:50:58 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=120</guid>
		<description><![CDATA[Depois de muito tempo sem escrever estou eu aqui de novo falando de JSF 2.0 Neste post irei mostrar como está ficando o suporte a ajax do JSF 2. Já adianto que está ficando bem parecido com o Ajax4Jsf. Em outros posts eu já havia comentado sobre o suporte a ajax que a nova versão [...]]]></description>
			<content:encoded><![CDATA[<p>Depois de muito tempo sem escrever estou eu aqui de novo falando de JSF 2.0</p>
<p>Neste post irei mostrar como está ficando o suporte a ajax do JSF 2. Já adianto que está ficando bem parecido com o Ajax4Jsf. Em outros posts eu já havia comentado sobre o suporte a ajax que a nova versão do jsf vai suportar. Mas agora vou falar do componente de tela para facilitar o uso, no outro post falei apenas da API JavaScript, que eu usei <a href="http://blog.gilliard.eti.br/2009/02/exemplo-com-jsf-2/">nesse exemplo</a>.</p>
<p>O componente &lt;f:ajax&gt; parece o &lt;a4j:support&gt;. Essa nova tag pode ser usada tanto dentro de uma tag específica, tornando-a ajax, assim como fazemos com o &lt;a4j:support&gt; ou pode ser colocada em volta de vários componentes, tornando todos os componentes dentro dela ajax.</p>
<p>Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGroup</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;panelGroupX&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;outputY&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">execute</span>=<span style="color: #ff0000;">&quot;@form&quot;</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;panelGroupX outputY&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Nesse exemplo temos uma página como já estamos acostumados, até onde o novo componente aparece. Nesse caso a tag &lt;f:ajax&gt; está habilitando ajax no commandButton, e os dois principais atributos da tag são &#8220;execute&#8221; e &#8220;render&#8221;. O primeiro serve para informarmos o que será enviado ao servidor na nossa requisição ajax, e o segundo é como o &#8220;reRender&#8221; do ajax4jsf, e serve para informarmos o que será renderizado novamente. Ambos aceitam uma lista de ids, separados por espaço em branco, ou então os seguintes valores pré-definidos:</p>
<ul>
<li><strong>@this</strong> &#8211; o próprio componente que dispara a requisição ajax</li>
<li><strong>@form</strong> &#8211; o formulário que envolve o componente @this</li>
<li><strong>@all</strong> &#8211; a view inteira</li>
<li><strong>@none</strong> &#8211; nenhum componente</li>
</ul>
<p>Lembrando novamente que esses valores servem tanto para informar o que vai (execute) e o que volta (render) em uma requisição ajax.</p>
<p>Agora outro exemplo</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">event</span>=<span style="color: #ff0000;">&quot;onmouseover&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGroup</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;panelGroupX&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;outputY&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;...&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:ajax</span> <span style="color: #000066;">event</span>=<span style="color: #ff0000;">&quot;action&quot;</span> <span style="color: #000066;">execute</span>=<span style="color: #ff0000;">&quot;@form&quot;</span> <span style="color: #000066;">render</span>=<span style="color: #ff0000;">&quot;panelGroupX outputY&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:ajax<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Nesse caso a tag &lt;f:ajax&gt; envolve os demais componentes, fazendo com que tudo que está dentro dela passe a disparar eventos ajax. Cada tipo de componente possui um evento padrão que dispara a requisição ajax: um input dispara a requisição quando tem seu valor alterado e um botão ou link quando é clicado, por exemplo.</p>
<p>Porém nesse exemplo eu especifiquei que o evento padrão que executará o ajax para todos os componentes dentro da tag &lt;f:ajax&gt; é o &#8220;onmouseover&#8221;, mas como mostrado no commandButton eu posso sobrescrever os valores definidos na tag &lt;f:ajax&gt; de fora com uma tag dentro do próprio componente. Eu usei a propriedade &#8220;<strong>event</strong>&#8220;, mas poderia ter usado qualquer outra na tag ajax de fora, fornecendo assim um mesmo comportamente default para todos.</p>
<p>No último exemplo usei a propriedade &#8220;<strong>event</strong>&#8220;, que como visto no exemplo serve para dizer qual evento executará a requisição ajax. Essa propríedade suporta todos os eventos DOM e ainda &#8220;valueChange&#8221; para componentes de entrada de dados (ou mais especificamente um EditableValueHolder) e &#8220;action&#8221; para componentes de ação (um ActionSource).</p>
<p>A tag &lt;f:ajax&gt; suporta ainda os atributos:</p>
<ul>
<li><strong>listener</strong> &#8211; serve para fazer binding com um método que a seguinte assinatura &#8220;<em>public void <nome>(javax.faces.event.AjaxBehaviorEvent event) throws javax.faces.event.AbortProcessingException</em>&#8220;. Com isso podemos executar um código java quando um evento qualquer é disparado.</li>
<li><strong>disabled</strong> &#8211; seria o equivalente ao rendered de um componente visual, se o valor definido aqui for true o suporta a ajax fica desabilitado.</li>
<li><strong>immediate</strong> &#8211; igual o immediate dos componentes jsf comuns.</li>
<li><strong>onevent</strong> &#8211; função js que será chamada quando o evento especificado for executado</li>
<li><strong>onerror</strong> &#8211; função js que será chamada quando um erro ocorrer na requisição</li>
</ul>
<p>Esse post foi curto por falta de tempo, mas novos posts virão em breve (assim espero ). Já estou com um exemplo pronto de implementação de conversation usando o suporte a escopos customizados do JSF 2.0, mas isso vai ter que ficar para o próximo post <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Exemplo com JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2009/02/exemplo-com-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2009/02/exemplo-com-jsf-2/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 20:44:56 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[Facelets]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=113</guid>
		<description><![CDATA[Na última sexta-feira, dia 30/01/2009, realizamos a primeira reunião de 2009 do JUGMS. Foi bem legal, contamos com mais de 100 pessoas. Nosso bate papo teve, além de conversarmos sobre os planos do JUGMS, dois assuntos bem interessantes. O Saulo falou um pouco sobre Análise e Projeto OO em Java, e eu sobre as novidades [...]]]></description>
			<content:encoded><![CDATA[<p>Na última sexta-feira, dia 30/01/2009, realizamos a primeira reunião de 2009 do <a href="http://www.jugms.com.br/reuniao-2009-1/" target="_blank">JUGMS</a>. Foi bem legal, contamos com mais de 100 pessoas. Nosso bate papo teve, além de conversarmos sobre os planos do JUGMS, dois assuntos bem interessantes. O <a href="http://sauloarruda.eti.br/" target="_blank">Saulo</a> falou um pouco sobre Análise e Projeto OO em Java, e eu sobre as novidades do JavaEE 6, parando um tempinho a mais na parte de JSF 2.0.</p>
<p>O tempo foi curto, e não deu pra explorar muito o exemplo, mas logo abaixo estou disponibilizando a apresentação (design show de bola <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> ) e o <a href="http://blog.gilliard.eti.br/arquivos/apresentacao-jsf2.war">projeto de exemplo usando JSF 2</a>. O exemplo foi feito usando Java 6 e tomcat 6.</p>
<div style="width:425px" id="__ss_6201887"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/gscordeiro/java-ee-nostrilhos" title="JavaEE nos trilhos">JavaEE nos trilhos</a></strong><object id="__sse6201887" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javaeenostrilhos-101216190606-phpapp01&#038;stripped_title=java-ee-nostrilhos&#038;userName=gscordeiro" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed name="__sse6201887" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javaeenostrilhos-101216190606-phpapp01&#038;stripped_title=java-ee-nostrilhos&#038;userName=gscordeiro" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="padding:5px 0 12px">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/gscordeiro">Gilliard Cordeiro</a>.</div>
</div>
<iframe src='http://player.vimeo.com/video/17458035?title=1&amp;byline=1&amp;portrait=1' width='400' height='300' frameborder='0'></iframe>
<p>Alguns pontos que eu procurei mostrar no exemplo foram:</p>
<h2>API AJAX do JSF 2.0</h2>
<p>No código do exemplo podemos ver trechos de código como este:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Salvar&quot;</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{estadoBean.salvar}&quot;</span></span>
<span style="color: #009900;"><span style="color: #000066;">onclick</span>=<span style="color: #ff0000;">&quot;return facesAjaxRequest(this, event, {inputs: 'formEstado', render: 'formEstado:listaEstados'})&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
...</pre></div></div>

<p>onde eu criei essa função js chamada <i>facesAjaxRequest</i> que encapsula a simples chamada ajax do jsf 2 que seria assim:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">jsf.<span style="color: #660066;">ajax</span>.<span style="color: #660066;">request</span><span style="color: #009900;">&#40;</span>element<span style="color: #339933;">,</span> event<span style="color: #339933;">,</span> options<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Essa funçao recebe o elemento que está disparando a ação (normalmente this), o evento e um mapa de parâmetros. Nesse mapa existem duas entradas: execute e render. No render, especificamos, separados pos espaços em branco, os clientIds dos componentes que serão renderizados novamente, e no execute passamos os valores a serem enviados ao server nessa requisição ajax.</p>
<p>No exemplo usei a função facesAjaxRequest para montar dinamicamente a lista que vai no parâmetro execute, por isso este parâmetro não aparece no primeiro exemplo mostrado. Com essa função, podemos ainda passar o id de qualquer elemento html pelo atributo inputs do mapa que todos os inputs e selects que estiverem abaixo desse elemento será enviado para o server. Na tela de cadastro de cidades fiz uma espécie de ajaxRegion usando essa forma bem simples.</p>
<p><del datetime="2010-12-17T01:11:04+00:00">Isso tudo porque o JSF 2 não tem algo tão fácil de usar como os componentes da biblioteca ajax4jsf. A idéia dessa biblioteca de ajax de jsf 2 não é deixar tudo mastigadinho, e sim prover uma infraestrutura básica uso padronizado de js nos componentes, eliminando ou diminuindo assim as incompatibilidades entre as bibliotecas de componentes disponíveis.</del></p>
<p><strong>Update:</strong> Na época do <em>Early Draft Review 2</em> só tínhamos a api js, mas logo depois saiu a tag estilo ajax4jsf e fiz <a href="http://blog.gilliard.eti.br/2009/05/ajax-no-jsf-2/">um outro post sobre isso</a>.</p>
<p>Para quem chegou a usar as funções js do Facelets 1.2, que nem chegou a ser continuado, e que eu mostrei num artigo que escrevi pra MundoJava há muito tempo, o funcionamento é quase o mesmo, só mudando praticamente o nome das funções js e a forma como os dados eram enviados ao server.</p>
<h2>Facelets 2</h2>
<p>Como já foi dito por aí, agora o JSF já vem por default com o Facelets 2 habilitado, não sendo necessário colocar nenhuma configuração para utilizálo. Inclusive no exemplo disponível para download, nem existe o arquivo faces-config.xml, pois fiz tudo por anotações e o Facelets já vem pronto pra uso. Mas é claro que ele continua sendo utilizado para as regras de navegação.</p>
<h2>Criação de componentes com Facelets 2</h2>
<p>Com facelets 2, a criação de componentes será algo mais &#8220;formal&#8221; do que fazemos com facelets hoje em dia. Isso graças a presença de uma definição do componente como esse:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:interface</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;beanSimples&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:attribute</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;bean&quot;</span> <span style="color: #000066;">required</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:attribute</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;descricao&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;String&quot;</span> <span style="color: #000066;">required</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:attribute<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:interface<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:implementation<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    Descrição: <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:inputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;descricao&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{compositeComponent.attrs.bean.descricao}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:implementation<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
...</pre></div></div>

<p>O componete possui a interface e a implementação. Na interface podemos colocar os parâmetros que serão recebidos, como no exemplo onde eu preciso passar um objeto que eu chamei de &#8220;bean&#8221; e esse bean tem que ter um atributo do tipo String chamado descrição.</p>
<p>É possível ainda passar atributos que representam ações, o que não é possível hoje em dia. Além disso não é necessário nenhum arquivo para configurar o nosso componente customizado, tudo é feito através de convenção. Basta colocar o componente em uma pasta dentro do resources do jsf que ele já fica publicado e acessível por uma uri default. Mas se quisermos colocar uma uri específica é só indicar através de um arquivo de configuração.</p>
<h2>SelectItems</h2>
<p>Finalmente podemos usar o componente f:selectItems sem ter que criar uma lista ou array de SelectItem. Agora podemos usar diretamente nossos objetos do modelo como podemos fazer usando outros componentes de selectItems como o do Seam.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:selectOneMenu</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{cidadeBean.cidade.estado}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:selectItems</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;#{estadoBean.estados}&quot;</span> <span style="color: #000066;">var</span>=<span style="color: #ff0000;">&quot;estado&quot;</span> <span style="color: #000066;">itemLabel</span>=<span style="color: #ff0000;">&quot;#{estado.descricao}&quot;</span> <span style="color: #000066;">itemValue</span>=<span style="color: #ff0000;">&quot;#{estado}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:selectOneMenu<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h2>Finalizando</h2>
<p>O exemplo disponível é bem simples, mas procurei mostrar nele o uso de coisas simples, como as mencionadas acima, e também proporcionar para quem ainda não teve a disposição de começar a testar que já tenha um ponto de partida. Olhando o código fonte podemos ver funcionando também as novas tags para escrever css e js, e explorar a parte de localização de recursos, que é inclusive o que torna a criação de componentes tão simples.</p>
<p>Espero que esse post e os materiais relacionados sejam de utilidade, e caso você encontre algum erro no material disponível me avise comentando aqui <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2009/02/exemplo-com-jsf-2/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>view scope no JSF 2.0</title>
		<link>http://blog.gilliard.eti.br/2008/10/view-scope-no-jsf-2/</link>
		<comments>http://blog.gilliard.eti.br/2008/10/view-scope-no-jsf-2/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 20:00:19 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=101</guid>
		<description><![CDATA[Eu uso JSF há um bom tempo e sempre fui um defensor de que JSF é muito bom, mas hoje em dia ainda não da pra usar ele sozinho, por isso mesmo uso JSF + Facelets + Seam. Acredito que com o que temos hoje usar JSF sozinho não é lá das coisas mais produtivas [...]]]></description>
			<content:encoded><![CDATA[<p>Eu uso JSF há um bom tempo e sempre fui um defensor de que JSF é muito bom, mas hoje em dia ainda não da pra usar ele sozinho, por isso mesmo uso JSF + Facelets + Seam. Acredito que com o que temos hoje usar JSF sozinho não é lá das coisas mais produtivas do mundo, e isso em alguns casos faz com que pessoas critiquem o JSF porque não querem adicionar mais dependências ao projeto e deixam Facelets e Seam de fora.</p>
<p>Pessoalmente eu acho isso quase o mesmo nível de querer fazer um projeto sem Hibernate pra não ter mais dependências no projeto. Tá certo que hoje o caso é diferente pois temos a JPA, mas se não a tivéssemos ainda, você faria um projeto de verdade só com JDBC só pra não ter essa dependência com Hibernate? Pois bem, muita gente faz isso com JSF. Mas assim como a JPA veio para deixar as pessoas mais tranquilas e menos apavoradas de ter um framework a mais na aplicação, o JSF 2.0 também vai dar uma forcinha nesse sentido. Com ele poderemos ter uma aplicação funcionando super bem sem adicionar outros frameworks para isso. E isso devido duas coisas: a inclusão do Facelets (já apresentada <a href="http://blog.gilliard.eti.br/2008/09/jsf-2-early-draft-review-2/">aqui</a>), e o novo escopo view.</p>
<h2>Erros de validação</h2>
<p>O JSF faz um papel muito bem feito abstraindo a camada web. Conseguimos desenvolver uma aplicação com JSF sem colocar a mão em HttpServletRequest e outros Http* da vida. O serviço seria muito bem feito de ponta a ponta se não fosse por um detalhe: a falta de um escopo que abstraísse também o http como o restante faz. Até o JSF 1.2 parece que essa parte foi esquecida, e enquanto o Faces tratava os escopos já conhecidos de toda aplicação web, como request, session e application, deixava uma porta aberta para o surgimento de componentes como t:saveState do Tomahawk, e depois as famosas conversations, no Seam.</p>
<p>Mas para que conversation e saveState servem? Um dos maiores problemas do JSF é a quantidade de &#8220;erro de validação&#8221; que acabam &#8220;estourando&#8221; na cara do desenvolvedor. Claro que sabendo como o JSF trabalha nós conseguimos desenvolver sem problemas. Eu sempre comento que a regra número 1 é sempre sobrescrever o método equals. Seguir boas práticas nunca é demais. E com isso boa parte dos erros de validação simplesmente somem. Um dia eu paro pra explicar melhor isso. Mas existem erros que acontecem como os famosos combos em cascata e commandButtons/commandLinks que não executam poque estão dentro de dataTable&#8217;s que só são preenchidas depois de alguma ação.</p>
<p>Imagine que temos uma página de cadastro de endereço, onde existem dois combos, o primeiro para estado e o segundo para cidades. Mas inicialmente o combo de cidades vem vazio, somente depois que selecionamos o primeiro, uma ação é executada para buscar as cidades. Selecionamos então &#8220;MS&#8221;, acontece uma nova requisição, as cidades são mostradas, selecionamos &#8220;Campo Grande&#8221; e mandamos salvar. Nisso vem o famoso erro de validação no combo das cidades. Isso acontece porque pela natureza stateless do managed bean de escopo request que estamos usando, o JSF esquece que já foi feita a requisição que busca as cidades, e para ele quando clicamos em salvar é como se fosse a primeira requisição. Então o JSF pensa: &#8220;como esse cara tá submetendo uma cidade sendo que eu nem mostrei os valores desse combo ainda? Essa cara tá me sacaneando, vou tesourar essa requisição dele&#8221;. Mas como fugir disso então? Coloca tudo no escopo de sessão? A resposta para esse problema é a utilização de escopos mais refinados, não disponíveis (ainda) no JSF padrão.</p>
<h2>Contextos mais &#8220;espertos&#8221;</h2>
<p>Na minha opinião, uma das melhores coisas do Seam é a conversação. Um conversação é um &#8220;escopo&#8221; maior que um request e menor que a sessão do usuário, e que tem um início e fim definidos por nós. Quando iniciamos uma conversação o contexto &#8220;vira&#8221; statefull até que seja finalizada, quando então &#8220;vira&#8221; stateless novamente. Claro que o Seam é muito mais que isso, mas para o assunto do post isso é o mais relevante. Fora <em>Conversation</em>, o Seam tem um escopo <em>Page</em>, cujo funcionamento é basicamente o mesmo do saveState. Dessa forma, o contexto é statefull enquanto submetemos para a mesma página. Uma conversação é algo mais refinado, que pode envolver várias telas, mas para a grande maioria dos casos essas várias requisições que precisamos manter o estado são feitas para mesma tela, como nos exemplos dos combos de estado e cidade e da dataTable resultando de filtro com uma action dentro.</p>
<h2>View Scope</h2>
<p>Exatamente nesse caso que o escopo <em>view</em> vem suprir essa carência do JSF padrão. Um managed bean com esse escopo permanece na memória enquanto submetemos para a mesma tela. Não quero dizer que você nunca mais vai precisar de outras coisas, ou que o Seam nada mais é do que fazer de outra forma o que um saveState já fazia antes, mas sim que agora para a maioria das aplicações já poderemos usar apenas JSF 2 sem ter que usar outras ferramentas para nos auxiliar. Claro que um conjunto de componentes ricos sempre será bem vindo, e que certamente iremos continuar querendo usar algumas coisas mais específicas que o Seam/WebBeans nos oferecem. Mas o grande ganho é que para o básico não precisamos de mais nada, coisa que infelizmente hoje, com JSF 1.2, ainda não acontece.</p>
<p>Como já escrevi bastante, vamos a um exemplo. O nosso managed bean de escopo view ficaria assim:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@ManagedBean<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;enderecoBean&quot;</span><span style="color: #009900;">&#41;</span>
@ViewScoped
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> EnderecoBean <span style="color: #009900;">&#123;</span>
&nbsp;
    @PostContruct
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> construct<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//chamado só quando o managed bean é colocado no escopo view,</span>
        <span style="color: #666666; font-style: italic;">//e não a cada requisição como acontecia com o escopo request</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @PreDestroy
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> destroy<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//chamado quando outra view for chamada através do UIViewRoot.setViewId(String viewId)</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Com esse escopo o JSF cria o managed bean na primeira requisição onde ele for preciso (se for lazy), e só o remove da memória quando for chamado o método UIViewRoot.setViewId(String viewId) para indicar que iremos trabalhar com outra página.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2008/10/view-scope-no-jsf-2/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>JavaServer Faces 2.0 &#8211; Early Draft Review 2</title>
		<link>http://blog.gilliard.eti.br/2008/09/jsf-2-early-draft-review-2/</link>
		<comments>http://blog.gilliard.eti.br/2008/09/jsf-2-early-draft-review-2/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 01:58:32 +0000</pubDate>
		<dc:creator>Gilliard Cordeiro</dc:creator>
				<category><![CDATA[Facelets]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.gilliard.eti.br/?p=71</guid>
		<description><![CDATA[Saiu o segundo rascunho da especificação do JSF 2.0, no entanto ainda não há uma versão da implementação da EDR2 disponível para download como já saiu para a EDR1. Primeiramente, vou me basear nas diferenças entre as reviews 1 e 2, mas isso não significa que o que vou falar aqui é inédito pois podemos [...]]]></description>
			<content:encoded><![CDATA[<p>Saiu o segundo rascunho da especificação do JSF 2.0, no entanto ainda não há uma versão da implementação da EDR2 disponível para download como já saiu para a EDR1.</p>
<p>Primeiramente, vou me basear nas diferenças entre as reviews 1 e 2, mas isso não significa que o que vou falar aqui é inédito pois podemos ver na net diversos post comentando <a href="http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature2">o que vem por aí</a>. E também ainda não li tudo, a idéia é compartilhar o que mais me chamou a atenção nesse primeiro contato.</p>
<h2>FacesContext</h2>
<p>Sem dúvida essa é uma das classes que mais manipulamos no JSF, e nela temos algumas funcionalidades novas interessantes:</p>
<ul>
<li><strong>getCurrentPhaseId</strong>() &#8211; Disponível desde a EDR1, devolve um <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/event/PhaseId.html">PhaseId</a>. Pode ser bem útil para fazermos algumas coisas só depois de uma de</code>determinada fase.</li>
<li><strong>getExecutePhaseClientIds</strong>() - Devolve uma List&lt;String&gt;. Guarda uma lista com os client ids dos componentes que serão processados na requisição atual. Isso porque o JSF2 tem nativamente o suporte à ajax, e submissão parcial da página.</li>
<li><strong>getPartialResponseWriter</strong>() - Devolve o <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/context/ResponseWriter.html">ResponseWriter</a> para os componentes de uma renderização parcial.</li>
<li><strong>getRenderPhaseClientIds</strong>() - Devolve uma List&lt;String&gt; contendo os client ids</code> dos componentes que serão renderizados em uma renderização parcial.</li>
<li><strong>isAjaxRequest</strong>() - devolve um boolean dizendo se a requisição é ajax (auto explicativa né <img src='http://blog.gilliard.eti.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</li>
<li><strong>isExecuteNone</strong>() - retorna true se for uma submissão parcial mas nenhum componente precisará ser processado. Seria como dar apenas um reRender usando o ajax4jsf mas sem mandar executar nada.</li>
<li><strong>isPostback</strong>() - método "atalho" para <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/render/ResponseStateManager.html#isPostback(javax.faces.context.FacesContext)">ResponseStateManager.isPostback(FacesContext)</a>.</li>
<li><strong>isRenderAll</strong>() - Retorna true se for uma requisição ajax, isRenderNone() retornar falso, e getRenderPhaseClientIds() retornar uma lista vazia.</li>
<li><strong>isRenderNone</strong>() - Retorna true caso for para executar uma renderização parcial, mas a lista de componentes a renderizar for vazia. Imagine uma requisição ajax que só envia dados ao servidor.</li>
</ul>
<p>Para os métodos get dessa lista, também tem os respectivos set.</p>
<h2>Annotations</h2>
<p>Uma coisa que todo mundo esperava está disponível no EDR2, que é a possibilidade de anotar nossos managed beans com <strong>@ManagedBean</strong>, <strong>@FacesValidator</strong>, <strong>@FacesConverter</strong> e <strong>@FacesComponent</strong> entre outros.</p>
<p>Para quem já está habituado com o <a href="http://www.seamframework.org">Seam</a> vai se sentir bem a vontade, pois as anotações seguem o mesmo estilo.</p>
<p>Apesar de no começo parecer estranho esse prefixo "Faces" em todas essas anotações, fica útil para não confundir com as interfaces com o mesmo nome. Sem isso (no Seam é assim), como importamos a anotação e a interface com o mesmo nome, uma das duas tem que ficar com o nome totalmente especificado. Não que seja problema, mas com esse prefixo fica mais "limpinho".</p>
<p><strong>@ManagedBean</strong></p>
<ul>
<li><strong>name</strong> - nome do managed bean</li>
<li><del datetime="2009-10-19T18:35:30+00:00"><strong>scope</strong>- escopo. O que não pareceu tão legal é que a gente passa uma String ("request", "session" ou "application"), quando seria mais bacana uma Enum como o Seam faz. O valor default é "none".</del></li>
<li><strong>eager</strong> - se for true, o managed bean será startado junto com a aplicação, e o "escope" passado será ignorado, e o managed bean será do escopo application. Se for false, fica como é hoje (lazy). O default é false.</li>
</ul>
<p><strong>@RequestScoped, @SessionScoped, @ApplicationScoped, @NoneScoped, <a href="http://blog.gilliard.eti.br/2008/10/view-scope-no-jsf-2/">@ViewScoped</a>, <a href="http://blog.gilliard.eti.br/2009/05/conversation-scope-usando-customscoped-do-jsf-2/">@CustomScoped</a></strong></p>
<ul>
<li>Cada uma das anotações representando seus respectivos escopos</li>
</ul>
<p><strong>@FacesConverter</strong></p>
<ul>
<li><strong>value</strong> - string que representa o <em>converter-id</em> do conversor</li>
<li><strong>forClass</strong> - passamos o java.lang.Class da classe que queremos registrar o conversor na forma de <em>converter-for-class</em></li>
</ul>
<p><strong>@FacesValidator</strong></p>
<ul>
<li><strong>value</strong> - string que representa o <em>validator-id</em> do validador</li>
</ul>
<p><strong>@FacesComponent</strong></p>
<ul>
<li><strong>value</strong> - string que representa o <em>component-type</em> do UIComponente</li>
</ul>
<h2>Facelets 2</h2>
<p>O outro assunto que de cara me interessou foi a integração do JSF com o Facelets, pois já uso Facelets há um bom tempo e nem me imagino fazendo uma aplicação em JSF sem ele. Tanto que até escrevi uma <a href="http://www.mundojava.com.br/NovoSite/21destaque.shtml">matéria pra a MundoJava</a> sobre Facelets e as novidades do JSF 1.2. Na época eu comentei sobre a versão 1.2 do Facelets que nunca chegou a sair, talvez porque o pessoal passou a investir no JSFTemplating ou quem sabe viram que compensaria partir logo para um 2.0. Mas no Facelets 1.2 já podíamos ver o que provavelmente foi a base da API de Ajax para o JSF2.</p>
<p>No JSF2 temos o chamado PDL (Page Declaration Language), que é uma abstração para os mecanismos de definição de páginas disponíveis para o JSF, que até agora são JSP e Facelets. Porém se a gente der uma espiadinha no projeto JSFTemplating, podemos ver que existe a possibilidade de usarmos outras coisas, como Groovy por exemplo. Então é bem possível que vejamos coisas parecidas para o JSF2. Só para concluir a idéia, já é possivel usar Groovy em vez de xhtml para construir telas com Facelets, usando <a href="http://gracelets.sourceforge.net/">Gracelets</a>. É bem bacana e eu já fiz uns testes que depois vou postar aqui também. Mas vamos voltar ao assunto.</p>
<p>Na EDR2 é explicado como será mantida a compatibilidade retroativa com as aplicações que usam Facelets. Basicamente será procurando dentro das classes da nossa aplicação ou das dependencias dela se existe alguma dependencia de classes do pacote com.sun.facelets e/ou dos seus subpacotes. Se houver, o Facelets embarcado no JSF não vai rodar, e as coisas vão continuar como estão, onde quem roda é o facelets que está no jar da nossa aplicação. Agora se não houver dependencia com as classes do Facelets atual, o Facelets2 entra em ação.</p>
<h3>Composition Component com JSF/Facelets 2</h3>
<p>Primeiramente, seria interessante dar uma olhada no <a href="http://blogs.sun.com/rlubke/entry/jsf_2_0_new_feature5">suporte a recursos</a> do JSF2 para entendermos melhor como tudo vai funcionar. Vou seguir o exemplo da documentação para facilitar.</p>
<p>Um composition component vai ser definifo usando o suporte a resources do JSF2. Imagine que o source do nosso componente é o <strong>foo.xhtml</strong> que está dentro da pasta <strong>ezcomp</strong> que por sua vez fica dentro da pasta de resources do JSF. Para usarmos esse componente nao precisamos mais de um arquivo taglib.xml, bastara chamarmos assim:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;</span>
<span style="color: #00bbdd;"> &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;html</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/1999/xhtml&quot;</span></span>
<span style="color: #009900;"> <span style="color: #000066;">xmlns:h</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/html&quot;</span></span>
<span style="color: #009900;"> <span style="color: #000066;">xmlns:f</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/core&quot;</span></span>
<span style="color: #009900;"> <span style="color: #000066;">xmlns:ui</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/facelets&quot;</span></span>
<span style="color: #009900;"> <span style="color: #000066;">xmlns:ez</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/composite/ezcomp&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
   ...
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ez:foo</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/html<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>Como podemos ver nossos componentes ficam automaticamente visíveis usando o padrão <em>http://java.sun.com/jsf/composite/&lt;composite-library-name&gt;</em> onde <em>&lt;composite-library-name&gt;</em> é o nome da nossa pasta dentro do resources do JSF. E cada xhtml dentro dessa pasta pode ser acessado como um componente. Vimos aqui um bom exemplo de <a href="http://en.wikipedia.org/wiki/Convention_over_Configuration">CoC</a> no JSF2. Agora se quisermos usar um padrão diferente de nomenclatura para nossos componentes, basta usar o bom e velho arquivo de configuração de taglibs do facelets.</p>
<p>Agora ainda seguindo o exemplo disponível na versão snapshot (e provavelmente será a mesma do EDR2), vamos ver como fica o código de um componente definido em um arquivo chamado loginPanel.xhtml</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;html</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/1999/xhtml&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:h</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/html&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:f</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/core&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:ui</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/facelets&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:composite</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/composite&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Not present in rendered output<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:interface</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;loginPanel&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">displayName</span>=<span style="color: #ff0000;">&quot;Very Simple Login Panel&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">preferred</span>=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">expert</span>=<span style="color: #ff0000;">&quot;false&quot;</span></span>
<span style="color: #009900;">                     <span style="color: #000066;">shortDescription</span>=<span style="color: #ff0000;">&quot;An illustration of the composite component feature&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:attribute</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;model&quot;</span> <span style="color: #000066;">required</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:attribute</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;loginAction&quot;</span> <span style="color: #000066;">required</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:deferred-method<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:method-signature<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                    java.lang.Object action()
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:method-signature<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:deferred-method<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:attribute<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:attribute<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:editableValueHolder</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;username&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:actionSource</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;loginEvent&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:actionSource</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;cancelEvent&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:actionSource</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;allEvents&quot;</span> <span style="color: #000066;">targets</span>=<span style="color: #ff0000;">&quot;loginEvent,cancelEvent&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:interface<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:implementation<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;table</span> <span style="color: #000066;">border</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;thead<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tr<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:insertFacet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tr<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/thead<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tbody<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tr<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;td<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:inputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;username&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;loginEvent&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Login&quot;</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;#{compositeComponent.attributes.model.loginAction}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;cancelEvent&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Cancel&quot;</span> <span style="color: #000066;">action</span>=<span style="color: #ff0000;">&quot;cancel&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:commandButton<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/td<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tr<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tr<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;td<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>This is the login panel footer<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite:insertChildren</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/td<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tr<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tbody<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/table<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite:implementation<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/html<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>Coloquei o código todo, mas o mais importante é da linha 12 até a linha 41, que é onde definimos as características do nosso componente. Isso deve facilitar que ferramentas deem suporte aos nossos componentes, e também a quem for usar esses componentes, pois damos mais informações a respeito das propriedades que ele precisa. A documentação diz que em muitos casos será possível construir componentes sem prover essas informações, deixando mais parecido com o que é hoje, mas diz também que falta definir um limite de até onde pode ser feito um componente sem especificar esse "contrato de uso".</p>
<p>Uma coisa interessante que pode ser vista nesse exemplo é a exigencia de um método chamado loginAction com uma assinatura específica dentro do objeto que for passado no atributo model.</p>
<p>O código que usa esse componente pode ser visto a seguir</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;html</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/1999/xhtml&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:h</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/html&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:f</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/core&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:ui</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/facelets&quot;</span></span>
<span style="color: #009900;">      <span style="color: #000066;">xmlns:ez</span>=<span style="color: #ff0000;">&quot;http://java.sun.com/jsf/composite/ezcomp&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>The Simplest EZComp Demo That Could Possibly Work<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/title<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:head<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>Login Panel Component<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ui:debug</span> <span style="color: #000066;">hotkey</span>=<span style="color: #ff0000;">&quot;p&quot;</span> <span style="color: #000066;">rendered</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;compositeComponent&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;grayBox&quot;</span> <span style="color: #000066;">style</span>=<span style="color: #ff0000;">&quot;border: 1px solid #090;&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ez:loginPanel</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;loginPanelInConsumingPage&quot;</span> <span style="color: #000066;">model</span>=<span style="color: #ff0000;">&quot;#{bean}&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:valueChangeListener</span> <span style="color: #000066;">for</span>=<span style="color: #ff0000;">&quot;username&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;#{bean.useridValueChangeListener}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:actionListener</span> <span style="color: #000066;">for</span>=<span style="color: #ff0000;">&quot;loginEvent&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;#{bean.loginEventListener}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:actionListener</span> <span style="color: #000066;">for</span>=<span style="color: #ff0000;">&quot;cancelEvent&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;#{bean.cancelEventListener}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:actionListener</span> <span style="color: #000066;">for</span>=<span style="color: #ff0000;">&quot;allEvents&quot;</span> <span style="color: #000066;">binding</span>=<span style="color: #ff0000;">&quot;#{bean.allEventsListener}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;f:facet</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;header&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:panelGroup</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;headerFacetInConsumingPage&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
          <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;this is the header facet in the consuming page&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:panelGroup<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/f:facet<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;h:outputText</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;childInConsumingPage&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;this is a child component in the consuming page&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ez:loginPanel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;p<span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #000000; font-weight: bold;">&lt;h:commandButton</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;reload&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/p<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:form<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/h:body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/html<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div>

<p>Nesse exemplo pode reparar da linha 18 a 21 que usamos os <strong>composite:actionSource</strong> definidos no componente como ganchos para pendurar nossos listeners.</p>
<p>Só lembrando que esses exemplos são em cima da EDR2 do JSF2, então tudo que foi visto aqui pode não ser igual ao que vai estar na versão final.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gilliard.eti.br/2008/09/jsf-2-early-draft-review-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

