Vamos começar criando uma classe Pessoa, ops os gets e sets eu cortei :D
public class Pessoa {
private String id;
private String nome;
@Override
public String toString() {
return "Pessoa{" + "id=" + id + ", nome=" + nome + '}';
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pessoa other = (Pessoa) obj;
if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
E agora o tão esperado conversor
@FacesConverter(forClass = MB.Pessoa.class, value = "pessoaConverter")
public class PessoaConverter implements Converter {
private String getStringKey(String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
System.out.println("Valor do getStringKey: " + sb.toString() + "| valor: " + value);
return sb.toString();
}
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
System.out.println("Estou recebendo a string " + value);
if (value == null || value.length() == 0) {
return null;
}
Pessoa pessoa = new Pessoa(value);
return pessoa;
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Pessoa) {
Pessoa o = (Pessoa) object;
System.out.println("O objeto veio como " + o.toString());
System.out.println("\tConver estou enviando a string" + getStringKey(o.getId()));
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Pessoa.class.getName());
}
}
}
Se estiver usando JPA uma dia é fazer o getAsObject assim
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
System.out.println("Estou recebendo a string " + value);
if (value == null || value.length() == 0) {
return null;
}
PessoaController controller = (PessoaController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "pessoaController");
return controller.ejbFacade.find(getKey(value));
return pessoa;
}
Espero ter ajudado, e a explicação mais didática vai ficar para depois!!! rs
Nenhum comentário:
Postar um comentário