JSF roda duas vezes

7 respostas
Psycopata

Alguém sabe porque o JSF roda duas vezes?

Deixa eu explicar melhor: quando algum elemente lança um submit, como um botão ou algum elemento com submit() no onchange, o JSF submete o formulário duas vezes. Alguém sabe o porquê?
E como posso resolver isso?

Essa dupla submissão implica em vários problemas, tal como definir um valor errado para uma variável!

7 Respostas

alves.Felipe

tb tenho esse problema… mas não sei como resolver ainda…:slight_smile:

G

se vc postar os fontes fica mais facil, so na teoria é mto vago …

Psycopata

Gimoz, postar o fonte fica meio inviável porque é extenso. Mas, se mesmo assim vc quiser, eu posto.

Mas adiantando, esse problema eu tenho em TODOS os projetos JSF. Qualquer um que eu fizer, quando debugo eu vejo o JSF seta duas vezes, todas as variáves. Inclusive, num projeto aqui, um colega usou javascript para garantir os valores certos, porque o JSF setava correto na primeira vez e depois setava com valores errados na segunda vez.

Mas acho essa solução eu gato, porque o correto é o JSF setar apenas uma vez as variáveis.

Outro problema em postar o código é que vc não vai ter o banco. De qualquer maneira, vc fala qual parte do código é necessário: Só o JSF, só os beans, só os arquivos de configuração, tudo.

G

olha … a principio so os jsp’s e os beans

Psycopata

ok.

O bean:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.bb.sigov.eventos.evt.controle;

import br.com.bb.sigov.eventos.evt.bean.CapilaridadeBean;
import br.com.bb.sigov.eventos.evt.bean.EventoBean;
import br.com.bb.sigov.eventos.evt.bean.MunicipioBean;
import br.com.bb.sigov.eventos.evt.bean.UfBean;
import br.com.bb.sigov.eventos.evt.dao.CapilaridadeDAO;
import br.com.bb.sigov.eventos.evt.dao.EventoDAO;
import br.com.bb.sigov.eventos.evt.dao.MunicipioDAO;
import br.com.bb.sigov.eventos.evt.dao.UfDAO;
import br.com.bb.sigov.utilitarios.Log;
import br.com.bb.sigov.utilitarios.Usuario;
import java.util.ArrayList;
import java.util.Collection;
import javax.faces.model.SelectItem;

/**
 *
 * @author f9343091
 */
public class CadastroEvento
{
    private int superEvento;
    private int capilaridade;
    private String nomeEvento;
    private String descricaoEvento;
    private int [] estados;
    private int codEstado;
    private int [] municipios;
    private int [] municSelec;
    private int [] removeMunic;
    
    private EventoBean evento;
    private Usuario usr;
    private Log log;

    public CadastroEvento()
    {
        log = new Log("EventosRegionais");

        /// TEMPORARIO
        evento = new EventoBean();
        usr = new Usuario();
        usr.setCD_PRF_DEPE("8593");
        /// FIM TEMPORARIO
    }
    // --- Operação de interface
    public Collection<SelectItem> getListaEventos()
    {
        Collection<SelectItem> lst = new ArrayList<SelectItem>();
        EventoBean [] rst = null;
        EventoDAO dao = new EventoDAO();
        if (usr.getPrefixo() == 8593)
            rst = dao.listaEventoGlobal();
        else
            rst = dao.listaSubEvento();
        lst.add( new SelectItem(-1, " Selecione um evento ") );
        lst.add( new SelectItem(0, " Evento Global ") );
        for (int i = 0; i < rst.length; i++ )
            lst.add( new SelectItem(rst[i].getCd_evt() , rst[i].getNm_evt() ) );
        return lst;
    }

    public Collection<SelectItem> getListaCapilaridade()
    {
        Collection<SelectItem> lst = new ArrayList<SelectItem>();
        CapilaridadeDAO dao = new CapilaridadeDAO();
        CapilaridadeBean [] rst = dao.listaCapilaridade();
        lst.add( new SelectItem(-1, " Selecione um evento ") );
        for (int i = 0; i < rst.length; i++)
            lst.add( new SelectItem(rst[i].getCd_cplr(), rst[i].getNm_cplr()) );
        return lst;
    }

    public String irAbrangencia()
    {
        evento.setCd_cplr(capilaridade);
        evento.setCd_sup_evt(superEvento);
        evento.setDcr_evt(descricaoEvento);
        evento.setNm_evt(nomeEvento);
        return "abrangencia_pag";
    }
    // --- operações de Banco.
    public void salvar()
    {
        int i = 0;
    }
    // ---  Dados capilaridade
    public boolean isNacional()
    {
        return capilaridade == 1;
    }
    public boolean isEstadual()
    {
        return capilaridade == 2;
    }
    public boolean isMunicipal()
    {
        return capilaridade == 3;
    }
    public boolean isDiretoria()
    {
        return capilaridade == 4;
    }
    public boolean isSuper()
    {
        return capilaridade == 5;
    }
    public boolean isSuperRegional()
    {
        return capilaridade == 6;
    }
    public boolean isDependencia()
    {
        return capilaridade == 7;
    }

    
    // ---  Dados abrangência  ------------
    public Collection<SelectItem> getListaEstatos()
    {
        Collection<SelectItem> rtn = new ArrayList<SelectItem>();
        UfDAO dao = new UfDAO();
        UfBean [] uf = dao.listaUf();
        for (int i = 0; i < uf.length; i++)
            rtn.add( new SelectItem( uf[i].getCd_uf(), uf[i].getNm_uf() ) );
        return rtn;
    };

    public Collection<SelectItem> getListaMunicipiosPorUf()
    {
        Collection<SelectItem> rtn = new ArrayList<SelectItem>();
        MunicipioDAO dao = new MunicipioDAO();
        dao.setCodUf( codEstado );
        MunicipioBean [] mun = dao.municCodUf();
        for (int i = 0; i < mun.length; i++)
            rtn.add( new SelectItem(mun[i].getCd_ibge(), mun[i].getNm_mun()) );
        return rtn;
    }

    public Collection<SelectItem> getListaMunicSelecionados()
    {
        Collection<SelectItem> rtn = new ArrayList<SelectItem>();
        MunicipioDAO dao = new MunicipioDAO();
        if ( (municipios != null) && ( municipios.length > 0) )
        {
            for (int i = 0; i < municipios.length; i++)
            {
                dao.setCodMunIbge( municipios[i] );
                MunicipioBean [] mun = dao.municCodIbge();
                rtn.add( new SelectItem(mun[0].getCd_ibge(), mun[0].getNm_mun()) );
            }
        }
        else
        {
            rtn.add( new SelectItem(0,"----") );
        }
        return rtn;
    }

    public void adiocionarMunicipios()
    {
        ArrayList<Integer> lst = new ArrayList<Integer>();
        for (int i = 0; ( (municipios != null) && (i < municipios.length) ); i++)
            lst.add( new Integer(municipios[i]) );
        for (int i = 0;( (municSelec != null) && (i < municSelec.length) ); i++)
            lst.add( new Integer(municSelec[i]) );
        if (lst != null)
        {
            int[] aux = new int[lst.size()];
            for (int i = 0;i < aux.length ; i++)
                aux[i] = lst.get(i).intValue();
            municSelec = aux;
        }
        municipios = null;
    }
    public void removerMunicipios()
    {
        ArrayList<Integer> rm = new ArrayList<Integer>();
        ArrayList<Integer> pos = new ArrayList<Integer>();
        for (int i = 0;( (municSelec != null) && (i < municSelec.length) ); i++)
            rm.add(municSelec[i]);

        for (int i = 0; ( (rm != null) && (i < rm.size() ) ); i++)
            for (int j = 0;( (removeMunic != null) && (j < removeMunic.length) ); j++)
                if ( rm.get(i).intValue() == removeMunic[j])
                    pos.add(i);

        for (int i = 0;(( pos != null) && (i < pos.size() ) ); i++)
            rm.remove(pos.get(i));
        if (pos != null)
        {
            int[] aux = new int[rm.size()];
            for (int i = 0; i < aux.length; i++)
                aux[i] = rm.get(i).intValue();
            municSelec = aux;
        }
    }
    //--- ----- ---- Getters and Setters ---- --- --- ----
    /**
     * @return the evento
     */
    public EventoBean getEvento()
    {
        return evento;
    }

    /**
     * @param evento the evento to set
     */
    public void setEvento(EventoBean evento)
    {
        this.evento = evento;
    }

    /**
     * @return the usr
     */
    public Usuario getUsr()
    {
        return usr;
    }

    /**
     * @param usr the usr to set
     */
    public void setUsr(Usuario usr)
    {
        this.usr = usr;
    }

    /**
     * @return the superEvento
     */
    public int getSuperEvento()
    {
        return superEvento;
    }

    /**
     * @param superEvento the superEvento to set
     */
    public void setSuperEvento(int superEvento)
    {
        this.superEvento = superEvento;
    }

    /**
     * @return the capilaridade
     */
    public int getCapilaridade()
    {
        return capilaridade;
    }

    /**
     * @param capilaridade the capilaridade to set
     */
    public void setCapilaridade(int capilaridade)
    {
        this.capilaridade = capilaridade;
    }

    /**
     * @return the nm_evento
     */
    public String getNomeEvento()
    {
        return nomeEvento;
    }

    /**
     * @param nm_evento the nm_evento to set
     */
    public void setNomeEvento(String nomeEvento)
    {
        this.nomeEvento = nomeEvento;
    }

    /**
     * @return the dcr_evento
     */
    public String getDescricaoEvento()
    {
        return descricaoEvento;
    }

    /**
     * @param dcr_evento the dcr_evento to set
     */
    public void setDescricaoEvento(String descricaoEvento)
    {
        this.descricaoEvento = descricaoEvento;
    }

    /**
     * @return the estados
     */
    public int[] getEstados()
    {
        return estados;
    }

    /**
     * @param estados the estados to set
     */
    public void setEstados(int[] estados)
    {
        this.estados = estados;
    }

    /**
     * @return the codEstado
     */
    public int getCodEstado()
    {
        return codEstado;
    }

    /**
     * @param codEstado the codEstado to set
     */
    public void setCodEstado(int codEstado)
    {
        this.codEstado = codEstado;
    }

    /**
     * @return the municipios
     */
    public int[] getMunicipios()
    {
        return municipios;
    }

    /**
     * @param municipios the municipios to set
     */
    public void setMunicipios(int[] municipios)
    {
        this.municipios = municipios;
    }

    /**
     * @return the municSelec
     */
    public int[] getMunicSelec()
    {
        return municSelec;
    }

    /**
     * @param municSelec the municSelec to set
     */
    public void setMunicSelec(int[] municSelec)
    {
        this.municSelec = municSelec;
    }

    /**
     * @return the removeMunic
     */
    public int[] getRemoveMunic()
    {
        return removeMunic;
    }

    /**
     * @param removeMunic the removeMunic to set
     */
    public void setRemoveMunic(int[] removeMunic)
    {
        this.removeMunic = removeMunic;
    }

}

1ª tela do JSP:

<%-- 
    Document   : gerenciamentoEvt
    Created on : 09/02/2009, 07:24:40
    Author     : f9343091
--%>

<%@ page import="java.util.*, java.text.*, br.com.bb.sigov.utilitarios.*" contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="usuario"  class="br.com.bb.sigov.utilitarios.Usuario" scope="session"/>
<jsp:setProperty name="usuario" property="*"/>

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

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="../sigovEstilo/icone" href="favicon.ico" type="image/x-icon" />
        <link href="../sigovEstilo/sigovCss.css" rel="stylesheet" type="text/css" />
        <link href="../css.css" rel="stylesheet" type="text/css" />
        <link rel="stylesheet" type="text/css" href="/EventosRegionais/faces/jsfcrud.css" />
        <title>Eventos Regionais - Gerenciamento</title>
    </head>
    <% String aplicativo = "Eventos Regionais"; %>
    <%@ include file="../sigovEstilo/titulo.jsp"%>
    <f:view>
        <h:form>
            <h:outputText value="Gerenciamento de Eventos"/>
            <br />
            <h:outputText value="Bem vindo ao Gerenciamento de Eventos. Neste local é possível criar, alterar e excluir algum evento"/>
            <h:outputText value="Por favor, siga os passos abaixo:"/>
            <br />
            <br />
            <h:outputText value="Dados gerais do Evento"/>
            <br />
            <br />
            <h:panelGrid columns="2" cellpadding="0" cellspacing="0" border="0">
                <h:outputText value="Nome do evento: "/>
                <h:inputText value="#{cadastroEvt.nomeEvento}" title="Define o nome do Evento"/>
                <h:outputText value="Tipo do evento: "/>
                <h:selectOneMenu value="#{cadastroEvt.superEvento}" title="Determina qual é o tipo de evento.\n\rCaso seja um evento Global, escolher a opção 'Global'.\n\rCaso seja um sub Evento, escolher qual é o evento principal.">
                    <f:selectItems value="#{cadastroEvt.listaEventos}"/>
                </h:selectOneMenu>
                <h:outputText value="Capilaridade: "/>
                <h:selectOneMenu value="#{cadastroEvt.capilaridade}" title="Defini qual é a capilaridade de abrangência do evento.">
                    <f:selectItems value="#{cadastroEvt.listaCapilaridade}"/>
                </h:selectOneMenu>
                <h:outputText value="Descrição: "/>
                <h:inputTextarea value="#{cadastroEvt.descricaoEvento}" title="Um breve texto que contém uma descrição sunsita do Evento"/>
            </h:panelGrid>
            <br />
            <h:commandButton value="Próximo >> " action="#{cadastroEvt.irAbrangencia}" />
        </h:form>
    </f:view>
    <p style="vertical-align:bottom">
        <%@ include file="../sigovEstilo/rodape.jsp"%>
    </p>
</html>

2ª tela do JSP

<%--
    Document   : gerenciamentoEvt
    Created on : 09/02/2009, 07:24:40
    Author     : f9343091
--%>

<%@ page import="java.util.*, java.text.*, br.com.bb.sigov.utilitarios.*" contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="usuario"  class="br.com.bb.sigov.utilitarios.Usuario" scope="session"/>
<jsp:setProperty name="usuario" property="*"/>

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

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="../sigovEstilo/icone" href="favicon.ico" type="image/x-icon" />
        <link href="../sigovEstilo/sigovCss.css" rel="stylesheet" type="text/css" />
        <link href="../css.css" rel="stylesheet" type="text/css" />
        <title>Eventos Regionais - Gerenciamento</title>
    </head>
    <% String aplicativo = "Eventos Regionais"; %>
    <%@ include file="../sigovEstilo/titulo.jsp"%>
    <f:view>
        <h:form>
            <h:outputText value="Gerenciamento de Eventos"/>
            <br />
            <h:outputText value="Agora é definida a abrangência de acordo com a capilaridade escolhida."/>
            <h:outputText value="Ex. se a capilaridade for Estadual, escolher qual(s) estado(s) faz(em) parte do projeto."/>
            <h:outputText value="Se a capilaridade for municipal, escolher qual(s) município(s). E assim é feito para cada nível escolhido."/>
            <h:outputText value="Por favor, siga os passos abaixo:"/>
            <br />
            <br />
            <h:outputText value="Dados da capilaridade"/>
            <br />
            <br />
            <h:panelGrid columns="2" cellpadding="0" cellspacing="0" border="0">
                <h:outputText value="Evento: "/>
                <h:outputText value="#{cadastroEvt.nomeEvento}"/>
            </h:panelGrid>
            <br />
            <!-- Acrescentar os paineis de acordo com a necessidade-->
            <h:panelGrid border="0" cellpadding="0" cellspacing="0" width="100%" rendered="#{cadastroEvt.estadual}">
                <f:subview id="cadAbgcEstado">
                    <%@ include file="cadAbgcEstado.jsp" %>
                </f:subview>
            </h:panelGrid>
            <h:panelGrid border="0" cellpadding="0" cellspacing="0" width="100%" rendered="#{cadastroEvt.municipal}">
                <f:subview id="cadAbgcMunicipios">
                    <%@ include file="cadAbgcMunicipios.jsp" %>
                </f:subview>
            </h:panelGrid>
            <!--  - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  -->
            <h:commandButton value="<< Anterior" action="evento_pag" />
            <f:verbatim>&nbsp;&nbsp;&nbsp;</f:verbatim>
            <h:commandButton value="Próximo >> " action="listaServicosMng_pag" />
        </h:form>
    </f:view>
    <p style="vertical-align:bottom">
        <%@ include file="../sigovEstilo/rodape.jsp"%>
    </p>
</html>

include da 2ª tela do JSP

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

<h:panelGrid columns="3" border="0" cellpadding="0" cellspacing="0" width="100%">
    <h:selectOneMenu value="#{cadastroEvt.codEstado}" onchange="submit()">
        <f:selectItems value="#{cadastroEvt.listaEstatos}"/>
    </h:selectOneMenu>
    <f:verbatim>
        <div style="overflow:auto;width:250px;height:200px">
            <h:selectManyCheckbox value="#{cadastroEvt.municipios}" layout="pageDirection">
                <f:selectItems value="#{cadastroEvt.listaMunicipiosPorUf}"/>
            </h:selectManyCheckbox>
        </div>
    </f:verbatim>
    <h:selectManyListbox value="#{cadastroEvt.removeMunic}">
        <f:selectItems value="#{cadastroEvt.listaMunicSelecionados}"/>
    </h:selectManyListbox>
    <f:verbatim></f:verbatim>
    <h:commandButton value="Adicionar" action="#{cadastroEvt.adiocionarMunicipios}"/>
    <h:commandButton value="Remover" action="#{cadastroEvt.removerMunicipios}"/>
</h:panelGrid>

Bom, tomare que ajude

Giulliano

Oi…não sei se eu entendi o que vc disse…mas não estou acreditando…

Vc esta confirmando que toda vez que faz um submit no seu formulário os métodos são chamados duas vezes ???

Vc já viu o lifecycle do jsf ( provavelmente sim…rss ) saberia dizer onde esta o seu problemas dentre essas fases ???

JSF for Non Belivers : http://www.ibm.com/developerworks/java/library/j-jsf2/

Psycopata

Pois é, é isso mesmo.

Eu já estudei o ciclo de vida do JSF e muitas coisas eu faço justamento porque eu sei qual é o comportamento do ciclo do vida e sei que vai funcionar. Mas essa dupla submissão é que até hoje eu não entendi o porque.

Criado 26 de fevereiro de 2009
Ultima resposta 27 de fev. de 2009
Respostas 7
Participantes 4