Navegação Estática e Dinâmica com JSF - Parte II

 

No artigo anterior começamos a utilizar Java Server Faces, mas não chegamos a usar nenhuma classe java, o nosso próximo exemplo utiliza um Action Controller, mas em artigos futuros usaremos exemplos mais realistas, por enquanto vamos dar continuidade o que começamos no artigo anterior.

 

cvnedjsfp2fig01.jpg 

Figura 1

 

A Figura1 mostra o funcionamento de nossa aplicação:

 

Atualize seu faces-config.xml com o conteúdo abaixo:

 

<?xml version="1.0"?>

<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>

<navigation-rule>

                        <from-view-id>/registrar1.jsp</from-view-id>

            <navigation-case>

                        <from-outcome>registrar</from-outcome>

                        <to-view-id>/WEB-INF/respostas/resultado1.jsp</to-view-id>

            </navigation-case>

</navigation-rule>

<navigation-rule>

            <from-view-id>/registrar2.jsp</from-view-id>

<navigation-case>

            <from-outcome>aceito</from-outcome>

            <to-view-id>/WEB-INF/respostas/aceito.jsp</to-view-id>

</navigation-case>

<navigation-case>

            <from-outcome>rejeitado</from-outcome>

            <to-view-id>/WEB-INF/respostas/rejeitado.jsp</to-view-id>

</navigation-case>

</navigation-rule>

            <managed-bean>

                        <managed-bean-name>PlanoSaudeController</managed-bean-name>

                        <managed-bean-class>navegacao.PlanoSaudeController</managed-bean-class>

                        <managed-bean-scope>request</managed-bean-scope>

            </managed-bean>

</faces-config>

 

Atualize também o arquivo web.xml:

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

    version="2.4">

  <display-name>MyFaces Application</display-name>

  <!-- servlet -->

  <servlet>

    <servlet-name>FacesServlet</servlet-name>

    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <!-- servlet-mapping -->

   <servlet-mapping>

    <servlet-name>FacesServlet</servlet-name>

    <url-pattern>*.faces</url-pattern>

  </servlet-mapping>

  <!-- The Usual Welcome File List -->

    <welcome-file-list>

      <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

   

<security-constraint>

<display-name>

Bloqueio  a acesso direto as paginas JSP.

</display-name>

<web-resource-collection>

<web-resource-name>Raw-JSF-JSP-Pages</web-resource-name>

<!-- Add url-pattern for EACH raw JSP page -->

<url-pattern>/welcome.jsp</url-pattern>

<url-pattern>/registrar1.jsp</url-pattern>

<url-pattern>/registrar2.jsp</url-pattern>

</web-resource-collection>

<auth-constraint>

<description>Sem regras, Apenas bloqueio  acesso direto</description>

</auth-constraint>

</security-constraint>

</web-app>

 

Crie o arquivo registrar2.jsp:

 

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>

            <head>

                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

                        <title>Plano de Saude JM</title>

            </head>

            <body>

            <div align="center">

                        <f:view>

                        <h1>Formulario de Cadastro</h1>

                                   <h:form>

                                   Nome: <h:inputText/><br>

                                   Telefone: <h:inputText /> <br>

                                   Cidade: <h:inputText /><br>

                                   Estado: <h:inputText /><br>

                                   <h:commandButton value="Inscrever" action="#{PlanoSaudeController.cadastrar}"/>

                                   </h:form>

                        </f:view>

                        </div>

            </body>

</html>

 

no pacote navegação crie a classe : PlanoSaudeController.java

 

package navegacao;

/**

 * Este exemplo não usa banco de dados e nem

 * usa coleções para armazenar dados em memória

 * O foco neste momento é apenas aos recursos do

 * framework JSF

 */

public class PlanoSaudeController {

            public String cadastrar(){

                        if (Math.random() < 0.2 ){

                                   return ("aceito");

                        }else

                                   return ("rejeitado");

            }

}

 

Em WEB-INF/respostas crie os arquivos: aceito.jsp e Rejeitado.jsp

Este é aceito.jsp:

 

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>

            <head>

                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

                        <title></title>

            </head>

            <body>

            <div align="center">

                        <f:view>

                        <h1>Congratulações</h1>

                                   <h:form>

                                   <h2>O seu Cadastramento foi recebido com sucesso!!!<br>

                                   Você é o nosso mais novo segurado</h2>

                                   <br>

            <a href="index.faces"> Voltar ao índice</a>

                                   </h:form>

                        </f:view>

                        </div>

            </body>

</html>

 

E aqui o código de rejeitado.jsp:

 

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>

            <head>

                        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

                        <title></title>

            </head>

            <body>

            <div align="center">

                        <f:view>

                                   <h1>Rejeitado</h1>

                                   <h:form>

                                   <h2>Infelizmente encontramos incompatibilidades com os dados

                                   fornecidos!<br>por favor tente novamente!</h2><br>

                        <a href="index.faces"> Voltar ao índice</a>

                                   </h:form>

                        </f:view>

                        </div>

            </body>

</html>

 

Mude o conteudo do arquivo index.jsp para ficar semelhante a esse:

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

   pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Registrar</title>

</head>

<body>

<a href="registrar1.faces">Registrar1 - Exemplo de Navegação Estática</a><br>

<a href="registrar2.faces">Registrar2 - Exemplo de Navegação Dinâmica</a><br>

</body>

</html>

 

As Figuras a seguir demonstram o funcionamento de nosso aplicativo:

 

cvnedjsfp2fig02.jpg 

Figura2

 

cvnedjsfp2fig03.jpg 

Figura3

 

cvnedjsfp2fig04.jpg 

Figura4

 

cvnedjsfp2fig05.jpg 

Figura5

 

Este artigo e o sua primeira parte tiveram como inspiração os livros Core Servlets de Marty Hall.