eventos jsf2

60
© 2007 Marty Hall Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. JSF: Manipulando Eventos

Upload: sparkynation

Post on 08-Mar-2015

58 views

Category:

Documents


1 download

TRANSCRIPT

© 2007 Marty Hall

Customized J2EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.Developed and taught by well-known author and developer. At public venues or onsite at your location.

JSF: Manipulando Eventos

2 J2EE training: http://courses.coreservlets.com

Topicos • Comparando action controllers com event

listeners• Action listeners• Mudança de valores com listeners• Usando JavaScript para enviar form

– Browser incompatibilidade• Combinando action listeners e action

controllers no mesmo elemento GUI

3 J2EE training: http://courses.coreservlets.com

Motivação• Há duas variações que iniciam evento

– Eventos do processamento back-end– Eventos que afetam somente o formato da interface do

usuário interface• JSF categoriza código que manipula essas

ações como action controllers e event listeners – Action controllers manipula a submissão do form

• Depois que o bean foi preenchido • Retorna strings que afeta a navegação

– Event listeners manipula eventos UI • Geralmente antes dos beans serem preenchidos• Nunca direciona a navegação

4 J2EE training: http://courses.coreservlets.com

JSF Fluxo de controle (Atualizado)

Blah.jsp(Runs bean getter methods)

GET requ

est Blah

.faces

submit formPOST request Blah.faces

Instantiate

Bean

return conditio

n

ChooseJSP

Run ActionController Method

forward result1.jspresult2.jsp...resultN.jsp(Use h:outputTextto display beanproperties)

Result of submission

Run Setter

Methods

faces-config.xml - beans declared in managed-bean section - mapping of return conditions declared in navigation-rule section

Business

Logic

Store results of businesslogic in bean

results

Button referred to action controller

Button or other control referred to

event listener

Efeito de apresentação

Redisplay form

5 J2EE training: http://courses.coreservlets.com

Tipos de Event Listeners• ActionListener

– Disparado pelo botão• <h:commandButton value="..." .../>• <h:commandButton image="..." .../>• <h:commandLink .../>

– Automatically submit the form• ValueChangeListener

– Disparado por combo boxes, checkboxes, radio buttons, textfields, e outros

• <h:selectOneMenu .../>• <h:selectBooleanCheckbox.../>• <h:selectOneRadio .../>• <h:inputText .../>

– Não envia o form

© 2007 Marty Hall

Customized J2EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.Developed and taught by well-known author and developer. At public venues or onsite at your location.

Action Listeners

7 J2EE training: http://courses.coreservlets.com

Usando ActionListener no JSF• Botões enviam um form e iniciam o

processamento no lado servidor– Use <h:commandButton action="..." ...>

• Alguns podem somente afetar a GUI– Use <h:commandButton actionListener="..." .../>– Quando quer que um processo ocorra antes do

preenchimento de beans e das validações necessárias.

<h:commandButton actionListener="..." immediate="true" .../>

8 J2EE training: http://courses.coreservlets.com

Implementado ActionListener em Java

• Listener ficam geralmente nas classes do bean

• Tem um ActionEvent como argumento Retorna Void (não uma String como em action

controllers)– ActionEvent está no javax.faces.event– ActionEvent tem um método getComponent que permite

obter uma referencia ao UIComponent • Do UIComponent, chega-se ao ID, renderer, e outras

informações– Exemplo

public void someMethod(ActionEvent event) { doSomeSideEffects();}

9 J2EE training: http://courses.coreservlets.com

Exemplo: Deixando o usuário desabilitar controles UI

• Todos controles UI tem uma propriedade a "disabled" que é falsa por default

• Usando um button com um ActionListener para desabilitar/habilitar um UI

• Exemplo específico– Coletar o nome e o trabalho para exibir um CV– Criar comboboxes que deixa o usuario selecionar a cores

para foreground e background <h:selectOneMenu value="..." disabled="..." ...> <f:selectItems value="..."/></h:selectOneMenu>

• Valores f:selectItems devem ser um array SelectItem – Tem botões que habilitam/desabilitam os comboboxes

10 J2EE training: http://courses.coreservlets.com

Passos criando o JSF1) Criar o beanA) Propriedade para os dados do formaB) Metodos para Action controller e event listener C) Placeholders para exibir os resultados2) Criar o form de entradaA) Campos de entrada relacionado com o bean B) Botão para o método action controllerque retorna a

condiçãoC) Botão ou outro controle GUI especifica o método event

listener 3) Editar faces-config.xmlA) Declarar the beanB) Especificar navigation rules4) Criar páginas resultados

11 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean• (A) Propriedade para o formpackage coreservlets;import javax.faces.model.*;import javax.faces.event.*;public class ResumeBean implements Serializable { ... private String fgColor = "BLACK"; private String bgColor = "WHITE"; private SelectItem[] availableColorNames = { new SelectItem("BLACK"), new SelectItem("WHITE"), new SelectItem("SILVER"), new SelectItem("RED"), new SelectItem("GREEN"), new SelectItem("BLUE") }; public String getFgColor() { return(fgColor); } public void setFgColor(String fgColor) { this.fgColor = fgColor; } ... public SelectItem[] getAvailableColors() {...}

12 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean(A) Propriedade para o form ... private String name = ""; private String jobTitle = ""; ... public String getName() { return(name); } public void setName(String name) { this.name = name; } public String getJobTitle() { return(jobTitle); } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; }

13 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean• (B) Event listener e action controller

public boolean isColorSupported() { return(isColorSupported); } public void toggleColorSupport(ActionEvent event) { isColorSupported = !isColorSupported; } public String showPreview() { if (isColorSupported && fgColor.equals(bgColor)) { return("same-color"); } else { return("success"); } }

Action listener

Action controller

14 J2EE training: http://courses.coreservlets.com

Passo 2: Criar Form de entrada• Novidades

– Use h:selectOneMenu para criar combobox– Use f:selectItems para preencher a lista– Use h:commandButton

• com actionListener e immediate– Faz com que o event listener seja disparado quando clicado

– Mude o label (valor) do botão dependendo do que ele faz• Neste caso, botão é toggle

• Exemplo <h:commandButton value="#{someBean.buttonLabel}" actionListener="#{someBean.doSideEffect}" immediate="true"/>

15 J2EE training: http://courses.coreservlets.com

Passo 2: Criar Form de entrada• (A)Campos de entrada<h:form> ... Foreground color: <h:selectOneMenu value="#{resumeBean.fgColor}" disabled="#{!resumeBean.colorSupported}"> <f:selectItems value="#{resumeBean.availableColors}"/> </h:selectOneMenu> <BR> Background color: <h:selectOneMenu value="#{resumeBean.bgColor}" disabled="#{!resumeBean.colorSupported}"> <f:selectItems value="#{resumeBean.availableColors}"/> </h:selectOneMenu><BR> ... Name: <h:inputText value="#{resumeBean.name}"/><BR> Job Title: <h:inputText value="#{resumeBean.jobTitle}"/><P></h:form>

16 J2EE training: http://courses.coreservlets.com

Passo 2: Criar Form de entrada• (B) Action controller

– Mesmo quando se tem event listeners, deve ter sempre action controllers

• Como antes, estes invocam a lógica de negocio e participam do fluxo de navegação (via navigation-rule)

<h:form> ... <h:commandButton value="Show Preview" action="#{resumeBean.showPreview}"/></h:form>

17 J2EE training: http://courses.coreservlets.com

Passo 2: Criar Form de entrada• (C) Event listener

– Event listeners executam efeitos do lado cliente, side effects, e o form é reapresentado

• Não invocam lógica de negocios, se nunca participam do fluxo de navegação (navigation-rule )

• Normalmente usa "immediate" para informar que os métodos setter não serão disparados

<h:form> ... <h:commandButton value="#{resumeBean.colorSupportLabel}" actionListener="#{resumeBean.toggleColorSupport}" immediate="true"/></h:form>

18 J2EE training: http://courses.coreservlets.com

Passo 2-4: Resultado inicial

19 J2EE training: http://courses.coreservlets.com

Passo 2: Resultado do botão Button (Independente do Action Controller)

20 J2EE training: http://courses.coreservlets.com

Passo 3: Editar faces-config.xml

• (A) Declarando bean– Note o escopo de sessão, então as mudanças persistem

…<faces-config> <managed-bean> <managed-bean-name>resumeBean</managed-bean-name> <managed-bean-class> coreservlets.ResumeBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>…</faces-config>

21 J2EE training: http://courses.coreservlets.com

Step 3: Editar faces-config.xml• (B) navigation rules

…<faces-config> … <navigation-rule> <from-view-id>/customize.jsp</from-view-id> <navigation-case> <from-outcome>same-color</from-outcome> <to-view-id>/WEB-INF/results/same-color.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/WEB-INF/results/show-preview.jsp</to-view-id> </navigation-case> </navigation-rule></faces-config>

22 J2EE training: http://courses.coreservlets.com

Passo 4: Criar páginas resutados

• WEB-INF/results/same-color.jsp

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><f:view><!DOCTYPE …><HTML>…You chose"<h:outputText value="#{resumeBean.fgColor}"/>"as both the foreground and background color. <P>You don't deserve to get a job, but I suppose we will let you <A HREF="customize.faces">try again</A>.…</HTML></f:view>

23 J2EE training: http://courses.coreservlets.com

Passo 4: Criar páginas resutados

• WEB-INF/results/show-preview.jsp<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><f:view><!DOCTYPE …><HTML>…<BODY TEXT="<h:outputText value="#{resumeBean.fgColor}"/>" BGCOLOR="<h:outputText value="#{resumeBean.bgColor}"/>"><H1 ALIGN="CENTER"><h:outputText value="#{resumeBean.name}"/><BR><SMALL><h:outputText value="#{resumeBean.jobTitle}"/></SMALL></H1>Experienced <h:outputText value="#{resumeBean.jobTitle}"/>seeks challenging position doing something.<H2>Employment History</H2>Blah, blah, blah, blah. Yadda, yadda, yadda, yadda.…</HTML></f:view>

24 J2EE training: http://courses.coreservlets.com

Passo 4: resutados

25 J2EE training: http://courses.coreservlets.com

Passo 4: resutados

© 2007 Marty Hall

Customized J2EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.Developed and taught by well-known author and developer. At public venues or onsite at your location.

Mudança de valores Listeners

27 J2EE training: http://courses.coreservlets.com

Usando ValueChangeListener em JSP

• ActionListener é associado a um botão– Form é automaticamente enviado

• ValueChangeListener é associado a combobox, listbox, radio button, checkbox, textfield, etc.– Form não são submetidos automaticamente– Necessário JavaScript para submeter o form

onclick="submit()" ou onchange="submit()"– Evento incompatibilidade entre Firefox e IE

• Firefox, Netscape, and Operapercebem a mudança• Internet Explorer só percebe depois que outro controle

recebe o foco

28 J2EE training: http://courses.coreservlets.com

Implementando ValueChangeListener

• Listener está na classe do bean

• Tem um ValueChangeEvent como argumento– Metodos uteis do ValueChangeEvent

• getComponent • getOldValue• getNewValue

– Sample codepublic void someMethod(ValueChangeEvent event) { boolean flag = ((Boolean)event.getNewValue()).booleanValue(); takeActionBasedOn(flag);}

29 J2EE training: http://courses.coreservlets.com

Exemplo: Mudando as cores listadas para FG e BG

• h:selectOneMenu usa f:selectItems • Use checkbox para chamar

ValueChangeListener• Definições das listas

– Color names– RGB values

30 J2EE training: http://courses.coreservlets.com

Passos criando o JSF1) Criar o beanA) Propriedade para os dados do formaB) Metodos para Action controller e event listener C) Placeholders para exibir os resultados2) Criar o form de entradaA) Campos de entrada relacionado com o bean B) Butão para o método action controllerque retorna a

condiçãoC) Botão ou outro controle GUI especifica o método event

listener 3) Editar faces-config.xmlA) Declarar the beanB) Especificar navigation rules4) Criar páginas resultados

31 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean• (A) Escolha de cores private SelectItem[] availableColorNames = { new SelectItem("BLACK"), new SelectItem("WHITE"), new SelectItem("SILVER"), new SelectItem("RED"), new SelectItem("GREEN"), new SelectItem("BLUE") }; private SelectItem[] availableColorValues = { new SelectItem("#000000"), new SelectItem("#FFFFFF"), new SelectItem("#C0C0C0"), new SelectItem("#FF0000"), new SelectItem("#00FF00"), new SelectItem("#0000FF") }; private boolean isUsingColorNames = true; public SelectItem[] getAvailableColors() { if (isUsingColorNames) { return(availableColorNames); } else { return(availableColorValues); } }

32 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean

• (B) Event listener– Quand checkbox é selecionada, muda as cores para

retornar RGB ao inves do nome return RGB values instead of color names

– Action controller, action listener, e outros dados do form iguais o exemplo anterior

public void changeColorMode(ValueChangeEvent event) { boolean flag = ((Boolean)event.getNewValue()).booleanValue(); setUsingColorNames(!flag);}

33 J2EE training: http://courses.coreservlets.com

Passo 2:Criar o Form (e especificar o Event Listener)

• Novidades– Use h:selectBooleanCheckbox para checkbox– Use valueChangeListener para associar event listener – Use onclick para submeter quando checkbox, mudar

• Exemplo<h:selectBooleanCheckbox valueChangeListener="#{resumeBean.changeColorMode}" onclick="submit()" immediate="true"/>

Client-side JavaScript code

34 J2EE training: http://courses.coreservlets.com

Passo 2: Resultado

35 J2EE training: http://courses.coreservlets.com

Passo 2: Resultado da mudança do Checkbox

36 J2EE training: http://courses.coreservlets.com

Passo 3-5• Iguais o exemplo anterior

© 2007 Marty Hall

Customized J2EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.Developed and taught by well-known author and developer. At public venues or onsite at your location.

Combinando Action Listeners e Action

Controllers no mesmo botão

38 J2EE training: http://courses.coreservlets.com

Motivação• Normalmente, action listeners e action

controllers são associados a botões diferentes

• As vezes, é necessário ambos– Listeners tem acesso a detalhes do GUI

• Renderer, client ID, etc.

• Exemplo: mapas server-side – h:commandButton com uma imagem ao invés do valor

resultado de um mapa

39 J2EE training: http://courses.coreservlets.com

Exemplo: escolhendo cor Background Color para uma imagem MAp

• Mostra uma barra grayscale para o usuario• Deixa ele clicar numa posição para escolher

background• Constrói o valor RGB

– le clientID.x valor– Normaliza para 0-256 baseado na largura– Gera uma saida em hex #RRGGBB string– Vai pro action listener

• Forward para o JSP – Feito pelo action controller

40 J2EE training: http://courses.coreservlets.com

Passos criando o JSF1) Criar o beanA) Propriedade para os dados do formaB) Metodos para Action controller e event listener C) Placeholders para exibir os resultados2) Criar o form de entradaA) Campos de entrada relacionado com o bean B) Butão para o método action controllerque retorna a

condiçãoC) Botão ou outro controle GUI especifica o método event

listener 3) Editar faces-config.xmlA) Declarar the beanB) Especificar navigation rules4) Criar páginas resultados

41 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean• (A) Form package coreservlets;...public class ColorBean { private String bgColor = "WHITE"; public String getBgColor() { return(bgColor); } public void setBgColor(String bgColor) { this.bgColor = bgColor; }

42 J2EE training: http://courses.coreservlets.com

Passo 1: Criar Bean• Listener procura valor x e cria uma corpublic void selectGrayLevel(ActionEvent event) { FacesContext context = FacesContext.getCurrentInstance(); String clientId = event.getComponent().getClientId(context); HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest(); String grayLevelString = request.getParameter(clientId + ".x"); int grayLevel = 220; try { grayLevel = Integer.parseInt(grayLevelString); } catch(NumberFormatException nfe) {} // Image is 440 pixels, so scale. grayLevel = (256 * grayLevel) / 440; String rVal = Integer.toString(grayLevel, 16); setBgColor("#" + rVal + rVal + rVal);}• Controller designa a pagina de saida public String showPreview() { return("success"); }

43 J2EE training: http://courses.coreservlets.com

Passp 2: criar o Form de entrada

• Especificar ambos o action and actionListener– Listener exeutam primeiro e tem acesso a detalhes

internos– use h:commandButton com uma imagem

• Resultado em um imagem do lado servidor• Code

<h:form> ... <h:commandButton image="images/GrayBar.gif" actionListener="#{colorBean.selectGrayLevel}" action="#{colorBean.showPreview}"/></h:form>

44 J2EE training: http://courses.coreservlets.com

Passo 2: Resultado

45 J2EE training: http://courses.coreservlets.com

Passo 3: Editar faces-config.xml

• Declarando o bean…<faces-config> ... <managed-bean> <managed-bean-name>colorBean</managed-bean-name> <managed-bean-class> coreservlets.ColorBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> …</faces-config>

46 J2EE training: http://courses.coreservlets.com

Passo 3: Editar faces-config.xml

• navigation rules…<faces-config> … <navigation-rule> <from-view-id>/customize-bg.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id> /WEB-INF/results/show-preview2.jsp </to-view-id> </navigation-case> </navigation-rule></faces-config>

47 J2EE training: http://courses.coreservlets.com

passo 4: Resultados• WEB-INF/results/show-preview2.jsp

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><f:view><!DOCTYPE ...><HTML><HEAD><TITLE>Preview of Background Color</TITLE></HEAD><BODY BGCOLOR="<h:outputText value="#{colorBean.bgColor}"/>"><H1 ALIGN="CENTER">Preview of Background Color</H1>Experienced employeeseeks challenging position doing something.<H2>Employment History</H2>Blah, blah, blah, blah. Yadda, yadda, yadda, yadda.…</HTML></f:view>

48 J2EE training: http://courses.coreservlets.com

passo 4: Resultados

© 2010 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Alterando o Locale Dinamicamente

J2EE training: http://courses.coreservlets.com

Configurar Locale baseado no usuário

• Duas Maneiras de configurar Locale– chamar setLocale no view

• <f:view locale="#{formSettings.currentLocale}">– Na aula anterior, configuramo a lingua baseado no

browser do usuário<f:view locale="#{facesContext.externalContext.request.locale}">

– Setar o Locale do UIViewRoot• FacesContext.getCurrentInstance().getViewRoot()

.setLocale(currentLocale);• I18N

– Aula anterior• <f:view

locale="#{facesContext.externalContext.request.locale}">5050

J2EE training: http://courses.coreservlets.com

Configurar Locale baseado no usuário

• Problema– Chamar o setLocale no view

• Disparado quando a página é recarregado• Não disparado após executar um action listener (ou

submeter um form)– Setar o Locale direto UIViewRoot

• Disparado após executar um action listener (ou submeter um form)

• Não mostrado quando a página é recarregada– Locale volta para o Deafult

• Solução– Fazer ambos!

5151

J2EE training: http://courses.coreservlets.com

Exemplo• Idéia

– Prover um pushbutton para alternar entre inglês e espanhol

• Abordagem– Criar dois arquivos de propriedades

• messages.properties and messages_es.properties– Prover um pushbutton que executa um action listener que

iá mudar o Locale• Diretamente setar o UIViewRoot• Settar um flag que determina o que o getLocale retorna

– No f:view, • <f:view locale="#{formSettings.locale}">

5252

J2EE training: http://courses.coreservlets.com

Input Form (register2.xhtml)<!DOCTYPE …><html …><f:view locale="#{formSettings.locale}">…<!-- Igual o customize.jsp. Exceto pelo view e pelo button --><h:commandButton value="#{msgs.switchLanguage}" actionListener="#{formSettings.swapLocale1}" immediate="true"/>…</f:view></html>

5353

J2EE training: http://courses.coreservlets.com

Bean para Action Listener(Parte chamada pelo f:view)

public class FormSettings implements Serializable { … //codigo do bean anterior private boolean isEnglish = true; private final Locale ENGLISH = Locale.ENGLISH; private final Locale SPANISH = new Locale("es");

public Locale getLocale() { if (isEnglish) { return(ENGLISH); } else { return(SPANISH); } }…

5454

J2EE training: http://courses.coreservlets.com

Bean para Action Listener( chamada pelo ActionListener)

public void swapLocale1(ActionEvent event) { switchLocale(); } private void switchLocale() { isEnglish = !isEnglish; Locale newLocale; if (isEnglish) { newLocale = ENGLISH; } else { newLocale = SPANISH; } FacesContext.getCurrentInstance().getViewRoot() .setLocale(newLocale); }

5555

J2EE training: http://courses.coreservlets.com

O restante igual• Sem mudanças do exemplo anterior

– Páginas de resultado• Também usam <f:view locale="#{formSettings.locale}"/>

5656

J2EE training: http://courses.coreservlets.com

Spanish Properties File(messages_es.properties)

registrationTitle=RegistrofirstName=Primer NombrelastName=ApellidoemailAddress=Dirección de EmailregistrationText=Incorpore Por Favor su {0}, {1}, y {2}.prompt=Incorpore {0}buttonLabel=ColoqúemesuccessTitle=ÉxitosuccessText=Se Registró con Éxito.switchLanguage=In EnglishnormalFont=Fuente NormallargeFont=Fuente GrandeerrorTitle=¡Error!missingData=Falta de input. Por favor, inténtelo de nuevo.

5757

Resultado: Form

5858

Resultado: Sucesso

6060

© 2007 Marty Hall

Customized J2EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.Developed and taught by well-known author and developer. At public venues or onsite at your location.

perguntas?