| :index-group: Misc |
| :jbake-type: page |
| :jbake-status: status=published |
| = Aplicação JSF que usa managed-bean e ejb |
| |
| Este é um aplicativo Web simples, que mostra como usar a injeção de dependência nos managed beans do JSF usando o TomEE. |
| |
| Ele contém um bean de sessão Stateless local `CalculatorImpl`, que adiciona dois números e retorna o resultado. O aplicativo também contém um managed beans do JSF `CalculatorBean`, que usa o EJB para adicionar dois números e exibir os resultados ao usuário. O EJB é injetado no managed beans usando a anotação `@ EJB`. |
| |
| == Uma pequena nota sobre a configuração: |
| |
| Você pode executar isso no Apache TomEE mais recente |
| https://repository.apache.org/content/repositories/snapshots/org/apache/tomee/apache-tomee/[snapshot] |
| |
| Quanto às bibliotecas, myfaces-api e myfaces-impl são fornecidos em tomee/lib e portanto, não devem fazer parte do war. Em termos práticos, eles estariam com o escopo `provided` |
| |
| Observe também que usamos a declaração do servlet 2.5 no web.xml |
| |
| [source,xml] |
| ---- |
| <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| xmlns="http://java.sun.com/xml/ns/javaee" |
| xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" |
| xsi:schemaLocation="http://java.sun.com/xml/ns/javaee |
| http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" |
| version="2.5"> |
| ---- |
| |
| E usamos a versão 2.0 do faces-config |
| |
| O código fonte completo é fornecido abaixo, mas vamos analisar alguns trechos menores e ver como ele funciona. |
| |
| Primeiro declararemos o `FacesServlet` no `web.xml` |
| |
| [source,java] |
| ---- |
| <servlet> |
| <servlet-name>Faces Servlet</servlet-name> |
| <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> |
| <load-on-startup>1</load-on-startup> |
| </servlet> |
| ---- |
| |
| O `FacesServlet` atua como o controlador mestre. |
| |
| Em seguida, criaremos o arquivo `calculator.xhtml`. |
| |
| [source,java] |
| ---- |
| <h:outputText value='Enter first number'/> |
| <h:inputText value='#{calculatorBean.x}'/> |
| <h:outputText value='Enter second number'/> |
| <h:inputText value='#{calculatorBean.y}'/> |
| <h:commandButton action="#{calculatorBean.add}" value="Add"/> |
| ---- |
| |
| Observe como usamos o bean aqui. Por padrão, o nome do Managed Bean é o nome da classe. |
| |
| Quando uma requisição é recebida, o bean é instanciado e colocado no escopo apropriado. Por padrão, o bean é colocado no escopo request. |
| |
| [source,java] |
| ---- |
| <h:inputText value='#{calculatorBean.x}'/> |
| ---- |
| |
| Aqui, o método `getX()` de calculatorBean é chamado e o valor resultante é exibido. `x` sendo um double, corretamente duplo, com razão, devemos ver 0.0 exibidos. |
| |
| Quando você altera o valor e envia o formulário, esses valores inseridos são vinculados usando os setters no bean e, em seguida, o método commandButton-action é chamado. |
| |
| Nesse caso, `CalculatorBean#add()` é chamado. |
| |
| `Calculator#add()` delega o trabalho para o ejb, obtém o resultado, |
| armazena e depois instrui qual visualização deve ser renderizada. |
| |
| Você está certo. O valor de retorno `success` é verificado nas regras de navegação faces-config e a respectiva página é renderizada. |
| |
| No nosso caso, a página `result.xhtml` é renderizada. |
| |
| O bean com escopo de request `calculatorBean` está disponível aqui e usamos EL para exibir os valores. |
| |
| == Fonte |
| |
| == Calculator |
| |
| [source,java] |
| ---- |
| package org.superbiz.jsf; |
| |
| import javax.ejb.Local; |
| |
| @Local |
| public interface Calculator { |
| public double add(double x, double y); |
| } |
| ---- |
| |
| == CalculatorBean |
| |
| [source,java] |
| ---- |
| package org.superbiz.jsf; |
| |
| import javax.ejb.EJB; |
| import javax.faces.bean.ManagedBean; |
| |
| @ManagedBean |
| public class CalculatorBean { |
| @EJB |
| Calculator calculator; |
| private double x; |
| private double y; |
| private double result; |
| |
| public double getX() { |
| return x; |
| } |
| |
| public void setX(double x) { |
| this.x = x; |
| } |
| |
| public double getY() { |
| return y; |
| } |
| |
| public void setY(double y) { |
| this.y = y; |
| } |
| |
| public double getResult() { |
| return result; |
| } |
| |
| public void setResult(double result) { |
| this.result = result; |
| } |
| |
| public String add() { |
| result = calculator.add(x, y); |
| return "success"; |
| } |
| } |
| ---- |
| |
| == CalculatorImpl |
| |
| [source,java] |
| ---- |
| package org.superbiz.jsf; |
| |
| import javax.ejb.Stateless; |
| |
| @Stateless |
| public class CalculatorImpl implements Calculator { |
| |
| public double add(double x, double y) { |
| return x + y; |
| } |
| } |
| ---- |
| |
| == web.xml |
| |
| [source,xml] |
| ---- |
| <?xml version="1.0"?> |
| |
| <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| xmlns="http://java.sun.com/xml/ns/javaee" |
| xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" |
| xsi:schemaLocation="http://java.sun.com/xml/ns/javaee |
| http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" |
| version="2.5"> |
| |
| <description>MyProject web.xml</description> |
| |
| <!-- Faces Servlet --> |
| <servlet> |
| <servlet-name>Faces Servlet</servlet-name> |
| <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> |
| <load-on-startup>1</load-on-startup> |
| </servlet> |
| |
| <!-- Faces Servlet Mapping --> |
| <servlet-mapping> |
| <servlet-name>Faces Servlet</servlet-name> |
| <url-pattern>*.jsf</url-pattern> |
| </servlet-mapping> |
| |
| <!-- Welcome files --> |
| <welcome-file-list> |
| <welcome-file>index.jsp</welcome-file> |
| <welcome-file>index.html</welcome-file> |
| </welcome-file-list> |
| </web-app> |
| ---- |
| |
| == Calculator.xhtml |
| |
| [source,xml] |
| ---- |
| <?xml version="1.0" encoding="UTF-8"?> |
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
| "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| <html xmlns="http://www.w3.org/1999/xhtml" |
| xmlns:f="http://java.sun.com/jsf/core" |
| xmlns:h="http://java.sun.com/jsf/html"> |
| |
| |
| <h:body bgcolor="white"> |
| <f:view> |
| <h:form> |
| <h:panelGrid columns="2"> |
| <h:outputText value='Enter first number'/> |
| <h:inputText value='#{calculatorBean.x}'/> |
| <h:outputText value='Enter second number'/> |
| <h:inputText value='#{calculatorBean.y}'/> |
| <h:commandButton action="#{calculatorBean.add}" value="Add"/> |
| </h:panelGrid> |
| </h:form> |
| </f:view> |
| </h:body> |
| </html> |
| ---- |
| |
| == Result.xhtml |
| |
| [source,xml] |
| ---- |
| <?xml version="1.0" encoding="UTF-8"?> |
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" |
| "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| <html xmlns="http://www.w3.org/1999/xhtml" |
| xmlns:f="http://java.sun.com/jsf/core" |
| xmlns:h="http://java.sun.com/jsf/html"> |
| |
| <h:body> |
| <f:view> |
| <h:form id="mainForm"> |
| <h2><h:outputText value="Result of adding #{calculatorBean.x} and #{calculatorBean.y} is #{calculatorBean.result }"/></h2> |
| <h:commandLink action="back"> |
| <h:outputText value="Home"/> |
| </h:commandLink> |
| </h:form> |
| </f:view> |
| </h:body> |
| </html> |
| ---- |
| |
| == faces-config.xml |
| |
| [source,xml] |
| ---- |
| <?xml version="1.0"?> |
| <faces-config xmlns="http://java.sun.com/xml/ns/javaee" |
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| xsi:schemaLocation="http://java.sun.com/xml/ns/javaee |
| http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" |
| version="2.0"> |
| |
| <navigation-rule> |
| <from-view-id>/calculator.xhtml</from-view-id> |
| <navigation-case> |
| <from-outcome>success</from-outcome> |
| <to-view-id>/result.xhtml</to-view-id> |
| </navigation-case> |
| </navigation-rule> |
| |
| <navigation-rule> |
| <from-view-id>/result.xhtml</from-view-id> |
| <navigation-case> |
| <from-outcome>back</from-outcome> |
| <to-view-id>/calculator.xhtml</to-view-id> |
| </navigation-case> |
| </navigation-rule> |
| </faces-config> |
| ---- |