[RESOLVIDO] Tráfego de dados em JSF + Primefaces - Dados não retornam

2 respostas
R

Bom dia pessoal,

Estou iniciando meus estudos em JSF + Primefaces, tentando fazer um Crud. Usei uns tutoriais como exemplo, pesquisei muito na internet e neste fórum mas não encontrei solução.

Fiz um cadastro simples de UF, com código, nome e sigla da UF.

Tenho uma classe modelo, uma classe DAO, uma classe Bean e o xhtml.

Liguei os inputTexts do xhtml aos atributos do objeto em questão da minha classe Bean.

Mando um comando pra salvar, e ele salva corretamente, porém não consigo recuperar os dados para o XHTML. Entre as classes java tudo bem, mas no View nada acontece, por exemplo: Se eu der um comando objeto = new Objeto(); ele não limpa os campos da view... se eu carregar um objeto, os dados também não são exibidos, embora o cadastro esteja persistindo normalmente...

Alguém poderia dar uma força?

Um abraço a todos, PAZ de Jah...

Segue os códigos:

MODEL:

package model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.hibernate.annotations.Index;

@Entity
public class Uf implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "cod_uf", nullable = false)
	private Integer cod_uf;

	@Index(name = "idx_nome")
	@Column(name = "nome", nullable = false, unique = true, length = 50)
	private String nome;
	
	@Column(name = "sigla", nullable = false, unique = true, length = 2)
	private String sigla;

	public Integer getCod_uf() {
		return cod_uf;
	}

	public void setCod_uf(Integer cod_uf) {
		this.cod_uf = cod_uf;
	}

	public String getNome() {
		return nome;
	}

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

	public String getSigla() {
		return sigla;
	}

	public void setSigla(String sigla) {
		this.sigla = sigla;
	}

}

DAO:

package dao;

import java.io.Serializable;
import java.util.List;
import utils.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.apache.log4j.Logger;
import model.Uf;

public class UfDao implements Serializable {

	private static final long serialVersionUID = 1L;

	private Session session;
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	private final String tabela = "Uf";

	public UfDao() {
		session = HibernateUtil.getSession();
		session.beginTransaction();		
	}

	public boolean salva(Uf classe) {	
		
		logger.debug("--> Salva " + tabela +": " + classe.getCod_uf() + " - "+ classe.getNome() );

		try {
						
			session.merge(classe);
			session.getTransaction().commit();			
		} catch (Exception e) {
			logger.error("# Erro salva " + tabela +": " + e.getMessage());
			session.getTransaction().rollback();
			return false;			
		}
		
		return true;
		
	}
	
	public boolean deleta(Uf classe) {
		
		logger.debug("--> Deleta" + tabela +": " + classe.getNome());
		
		try {
			session.delete(classe);
			session.getTransaction().commit();			
		} catch (Exception e) {
			logger.error("# Erro deleta " + tabela +": " + e.getMessage());
			session.getTransaction().rollback();
			return false;			
		}
		
		return true;
		
	}	

	@SuppressWarnings("all")
	public List getAll() {
		
		Query query = session.createQuery("from " + tabela + " order by nome asc" );
		return query.list();

	}

	@SuppressWarnings("all")
	public Uf getByCodigo(int cod_uf) {

		Query query = session.createQuery("from " + tabela + " where cod_uf = " + cod_uf);

		if (query.list().size() > 0) {

			Uf uf = (Uf) query.list().get(0);

			return uf;

		}

		return null;
		
	}
	
	@SuppressWarnings("all")
	public List getCampo(String campo, String valor) {

		Query query = session.createQuery("from " + tabela + " where " + campo
				+ " like '%" + valor + "%'");
		return query.list();
	}
	
}

BEAN:

package script;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;

import model.Uf;
import dao.UfDao;

@ManagedBean(name="CadUf")
@ViewScoped
public class CadUf implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private Uf uf = new Uf();
	
	public Uf getUf() {
		return uf;
	}

	public void setUf(Uf uf) {
		this.uf = uf;
	}

	public void novo() {
		uf = new Uf();		
	}
	
	public void salvar() {
		
		UfDao ufdao = new UfDao();
		
		ufdao.salva(uf);
		
	}
	
	public void carregar() {
		
		UfDao ufdao = new UfDao();
		
		uf = ufdao.getByCodigo(41);
		
	}

}

VIEW:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:h="http://java.sun.com/jsf/html"  
    xmlns:f="http://java.sun.com/jsf/core"  
    xmlns:p="http://primefaces.org/ui">
<h:head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Cadastro de UF</title>
</h:head>
<h:body>

<h:form prependId="false">
		<p:panel header="Cadastro de Uf">
			<h:panelGrid columns="2">
			
			Código: <h:inputText value="#{CadUf.uf.cod_uf}" size="50" id="codigo"/>
			Nome: <h:inputText value="#{CadUf.uf.nome}" size="50" id="nome"/>
			Sigla: <h:inputText value="#{CadUf.uf.sigla}" size="50" id="sigla"/>		
				
			<p:commandButton value="Salvar" action="#{CadUf.salvar}"/>
			
			<p:commandButton value="Carregar" action="#{CadUf.carregar}"/>
			
			<p:commandButton value="Novo" action="#{CadUf.novo}"/>
			
			</h:panelGrid>
		</p:panel>
	</h:form>

</h:body>
</html>

2 Respostas

A

Torque a action por actionListener e adicione nos teus botões update="@form", assim você não sairá do escopo da view.

R

Opaa… valeeuu andre.froes

era isso mesmo… obrigado… abraço!

Criado 30 de agosto de 2012
Ultima resposta 30 de ago. de 2012
Respostas 2
Participantes 2