[RESOLVIDO] Dúvida JSF - SelectItem não carrega e carregar campos com dados do mysql

8 respostas
vitaaoo

Boa noite!!

Eu queria que vcs dessem uma olhada no meu código e me informem o que eu estou fazendo errado por favor.

MEU XHTML
<?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">
<ui:component xmlns="http://www.w3.org/1999/xhtml"
              xmlns:ui="http://java.sun.com/jsf/facelets"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:p="http://primefaces.prime.com.tr/ui"
              xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Sistema Academico - Cadastro Aluno</title>
    </h:head>
    <h:body >
        <p:dialog id="dlgaluno"  header="Cadastrar Aluno" widgetVar="dlgAluno" width="450"
                  modal="true" >

            <fieldset style="border: #036fab; border-style: outset;">
                <legend>Sistema Academico - Cadastro Aluno</legend>
                <h:form>
                    <h:panelGrid columns="2" cellpadding="5">
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Código: *" />
                        <h:inputText style="width: 220px; height: 20px" id="codigo"  readonly="" value="#{Aluno.codigo}" />
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Nome Completo: *" />
                        <h:inputText style="width: 220px; height: 20px" value="#{Aluno.nome}" />
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Email: *" />
                        <h:inputText style="width: 220px; height: 20px" value="#{Aluno.email}" />
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Senha: *" />
                        <h:inputSecret style="width: 220px; height: 20px" value="#{Aluno.senha}" />
                        
                        
                        <f:facet name="footer">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;
                            
                            <p:commandButton style="width: 100px; align: right;" value="Salvar" update="growl"
                                             actionListener="#{Aluno.save}" />
                            <p:commandButton style="width: 100px; align: right;" value="Excluir" update="growl" 
                                             actionListener="#{Aluno.excluir}" />
                            
                        </f:facet>
  
                    </h:panelGrid>
                    <h:panelGrid columns="2" cellpadding="5">
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Código: " />
                        <h:inputText style="width: 220px; height: 20px" id="codigo1"  readonly="" value="#{Aluno.codigo}" />
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Nome: " />
                        <h:inputText style="width: 220px; height: 20px" value="#{Aluno.nome}" />
                        <h:outputLabel style="width: 170px; height: 20px" for="nome" value="Lista Alunos" />
                        <h:selectOneListbox style="width: 170px; height: 30px" value="#{Aluno.selectedItem}" size="1">
                            <f:selectItems id="selectItem"  value="#{Aluno.selectItems}"/>
                        </h:selectOneListbox>

                   
                         <f:facet name="footer">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;
                        <p:commandButton  style="width: 100px; align: right;"  value="Localizar" update="selectItem"
                                             actionListener="#{Aluno.localiza}" />
                        <p:commandButton style="width: 100px;" value="Editar" update="growl" 
                                             actionListener="#{Aluno.save}" />
                        </f:facet>
                    </h:panelGrid>     
                
                </h:form>
            </fieldset>
        </p:dialog>
    </h:body>
</ui:component>
CLASSE ALUNO
package br.com.SistemaAcademico.Bean;


import br.com.SistemaAcademico.ManageBean.AlunoManageBean;
import java.util.ArrayList;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 */

@ManagedBean(name="Aluno")
@SessionScoped
public class Aluno {
    private Integer codigo;
    private String nome;
    private String email;
    private String senha;
    
    private String selectedItem;
    private ArrayList<String> selectItems;
    

    public String getSelectedItem() {
        return selectedItem;
    }

    public void setSelectedItem(String selectedItem) {
        this.selectedItem = selectedItem;
    }

    public Integer getCodigo() {
        return codigo;
    }

    public void setCodigo(Integer codigo) {
        this.codigo = codigo;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public ArrayList<String> getSelectItems() {
        return selectItems;
    }

    public void setSelectItems(ArrayList<String> selectItems) {
        this.selectItems = selectItems;
    }

    
    public void save(ActionEvent event){
       AlunoManageBean user =  new AlunoManageBean();
       
       user.salvar(this);

    }
    
    
    public void localiza(ActionEvent event){
    
        AlunoManageBean bean = new AlunoManageBean();
        setSelectItems(bean.buscar(this));
        System.out.println("TESTANDO: "+selectItems.get(0));
        System.out.println("TESTANDO: "+selectItems.get(1));
    }
    
    public void editar(ActionEvent e){
    //EIS A MINHA DUVIDA MAIOR COMO CARREGAR OS CAMPOS DA PAGINA WEB AO AO CLICAR NO BOTAO EDITAR
    
    }
    
    public void excluir(ActionEvent e){
        
    
    }

}

Como voces podem ver eu coloquei 2 println ali pra conferir se o arraylist está mesmo sendo carregado.

Ao pesquisar com a palavra "teste" obtive 2 retornos, ou seja, esta carregando perfeitamente ... por tanto o erro esta dai pra frente.
INFO: TESTANDO: teste
INFO: TESTANDO: teste3

Por fim eu gostaria de saber. Ao selecionar o item no selectItem como eu carrego os dados da tabela nos campos do xhtml ?

Desde já. Obrigado!!

8 Respostas

tiago.vt

Você ta criando, uma lista de String, e passando pro selectItem, você tem que cria uma lista de SelectItem …

vitaaoo

Tiago eu tentei criar a lista de selectItem mas da uma mensagem de erro … eu tenho que criar uma classe selectItem entao ?

tiago.vt

private List selectItems = new ArrayList();

a lista vai da vazia depois vc cria 1 metodo que preencha com o conteudo que vc quer…

Diego_Adriano
Cara .. o problema é que n exibe os dados na pagina ?
<h:selectOneListbox style="width: 170px; height: 30px" value="#{Aluno.selectedItem}" size="1">  
                            <f:selectItems id="selectItem"  value="#{Aluno.selectItems}"/>  
                        </h:selectOneListbox>
Veja um correto:
<p:selectOneMenu id="cliente-instrutor" value="#{clienteBean.professorID}" required="true">
											
                  <f:selectItems 
					value="#{funcionarioBean.funcionarios}"
					var="funcionarios"
					itemLabel="#{funcionarios.nome}"
					itemValue="#{funcionarios.id}"/>
</p:selectOneMenu>
Se for isso ..
vitaaoo
tiago.vt:
private List selectItems = new ArrayList();

a lista vai da vazia depois vc cria 1 metodo que preencha com o conteudo que vc quer...

Eu fiz isso.

private ArrayList<SelectItem> selectItems;
private ArrayList<String> aux;
public void localiza(ActionEvent event){
    
        AlunoManageBean bean = new AlunoManageBean();
        aux = bean.buscar(this);
        try{ 
        for(int i=0;i<aux.size();i++){
        selectItems.add(new SelectItem(aux.get(i)));
        }
        }catch (Exception e){
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, " Erro no método localiza" , e.getMessage()+ "::::"+e.getCause());
            FacesContext.getCurrentInstance().addMessage(null, msg);}
    }
mas deu esse erro "Erro no método localiza null::::null"

nao tinha iniciado o private ArrayList selectItems;
dei um new ArrayList(); e parou de dar erro ... porém continua sem aparecer no

vitaaoo
Diego Adriano:
Cara .. o problema é que n exibe os dados na pagina ?
<h:selectOneListbox style="width: 170px; height: 30px" value="#{Aluno.selectedItem}" size="1">  
                            <f:selectItems id="selectItem"  value="#{Aluno.selectItems}"/>  
                        </h:selectOneListbox>
Veja um correto:
<p:selectOneMenu id="cliente-instrutor" value="#{clienteBean.professorID}" required="true">
											
                  <f:selectItems 
					value="#{funcionarioBean.funcionarios}"
					var="funcionarios"
					itemLabel="#{funcionarios.nome}"
					itemValue="#{funcionarios.id}"/>
</p:selectOneMenu>
Se for isso ..
no meu caso ficaria assim ?
<h:outputLabel style="width: 170px; height: 20px" for="nome" value="TESTE" />
                        <p:selectOneMenu id="cliente-instrutor" value="#{Aluno.selectedItem}" required="true">                        
                        <f:selectItems   
                            value="#{Aluno.selectItems}"  
                            var="aluno"  
                            itemLabel="#{Aluno.nome}"  
                            itemValue="#{Aluno.codigo}"/>  
                        </p:selectOneMenu>
vitaaoo

Valeu ae moçada consegui resolver.

Resolvi assim.

Adicionei um id no PANELGRID

<h:panelGrid id="tabela2 "columns="2" cellpadding="5">

e la no botão LOCALIZAR eu alterei o update

<p:commandButton style="width: 100px; align: right;" value="Localizar" update="tabela2" actionListener="#{Aluno.localiza}" />

Bom resolvido esse problema eu queria saber agora como depois de selecionar um desses alunos eu clico no botao EDITAR e os dados desse aluno sao carregados nos campos de cima ???

vitaaoo

Bom consegui resolver o outro problema tambem ...

public void editar(ActionEvent e){
    AlunoManageBean bean = new AlunoManageBean();
    Aluno temp = new Aluno();
    temp = bean.buscarAluno(getSelectedItem());
        this.codigo = temp.getCodigo();
        this.nome = temp.getNome();
        this.email = temp.getEmail();
        this.senha = temp.getSenha();
        this.cod_busca = temp.getCod_busca();
        this.nome_busca = temp.getNome_busca();
        
    }
Criado 29 de novembro de 2011
Ultima resposta 30 de nov. de 2011
Respostas 8
Participantes 3