Show data in a Datatable + JSF + Primefaces + CDI + Managedbean

Asked

Viewed 339 times

3

Talk to me, people! I’m having a problem to popular a Datatable, I’m using Jsf, CDI.

I believe that the name of teacher is coming normal because he is an object and the pupil is a List, But I don’t know how to fix it. I’m trying to get the attribute nome in class Usuario that belongs to the Aluno as follows:

GestaoProjetosBean(my design bean) -> Aluno.java-> Usuario.java -> nome

And I get the following mistake:

nov 12, 2017 6:42:24 pm com.sun.faces.application.view.Faceletviewhandlingstrategy handleRenderException GRAVE: Error Rendering View[/pages/Gestaoprojetos.xhtml] java.lang.Numberformatexception: For input string: "user" at java.lang.Numberformatexception.forInputString(Unknown Source) at java.lang.Integer.parseint(Unknown Source) at java.lang.Integer.parseint(Unknown Source) at javax.el.Listelresolver.coerce(Listelresolver.java:150) at javax.el.Listelresolver.getValue(Listelresolver.java:67) at com.sun.faces.el.Demuxcompositeelresolver. _getValue(Demuxcompositeelresolver.java:176) at com.sun.faces.el.Demuxcompositeelresolver.getValue(Demuxcompositeelresolver.java:203) at org.apache.el.parser.Astvalue.getValue(Astvalue.java:169) at org.apache.el.ValueExpressionImpl.getValue(Valueexpressionimpl.java:184) at org.jboss.Weld.el.Weldvalueexpression.getValue(Weldvalueexpression.java:50) at com.sun.faces.facelets.el.TagValueExpression.getValue(Tagvalueexpression.java:109) at javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:194) at javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:182) at javax.faces.Component.UIOutput.getValue(Uioutput.java:174) at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(Htmlbasicinputrenderer.java:205) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(Htmlbasicrenderer.java:355) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(Htmlbasicrenderer.java:164) at javax.faces.Component.UIComponentBase.encodeEnd(Uicomponentbase.java:920) at javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1863) at org.primefaces.Component.column.Column.renderChildren(Column.java:352) at org.primefaces.Component.datatable.Datatablerenderer.encodeCell(Datatablerenderer.java:1051) at org.primefaces.Component.datatable.Datatablerenderer.encodeRow(Datatablerenderer.java:999) at org.primefaces.Component.datatable.Datatablerenderer.encodeRows(Datatablerenderer.java:907) at org.primefaces.Component.datatable.Datatablerenderer.encodeTbody(Datatablerenderer.java:854) at org.primefaces.Component.datatable.Datatablerenderer.encodeTbody(Datatablerenderer.java:814) at org.primefaces.Component.datatable.Datatablerenderer.encodeRegularTable(Datatablerenderer.java:290))

nov 12, 2017 6:42:24 pm com.sun.faces.context.Exceptionhandlerimpl log FATAL: JSF1073: java.lang.Numberformatexception obtained during processing of RENDER_RESPONSE 6: Uicomponent-Clientid=, Message=For input string: "user" nov 12, 2017 6:42:24 pm com.sun.faces.context.Exceptionhandlerimpl log FATAL: For input string: "user" java.lang.Numberformatexception: For input string: "user" at java.lang.Numberformatexception.forInputString(Unknown Source) at java.lang.Integer.parseint(Unknown Source) at java.lang.Integer.parseint(Unknown Source) at javax.el.Listelresolver.coerce(Listelresolver.java:150) at javax.el.Listelresolver.getValue(Listelresolver.java:67) at com.sun.faces.el.Demuxcompositeelresolver. _getValue(Demuxcompositeelresolver.java:176) at com.sun.faces.el.Demuxcompositeelresolver.getValue(Demuxcompositeelresolver.java:203) at org.apache.el.parser.Astvalue.getValue(Astvalue.java:169) at org.apache.el.ValueExpressionImpl.getValue(Valueexpressionimpl.java:184) at org.jboss.Weld.el.Weldvalueexpression.getValue(Weldvalueexpression.java:50) at com.sun.faces.facelets.el.TagValueExpression.getValue(Tagvalueexpression.java:109) at javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:194) at javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:182) at javax.faces.Component.UIOutput.getValue(Uioutput.java:174) at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(Htmlbasicinputrenderer.java:205) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(Htmlbasicrenderer.java:355) at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(Htmlbasicrenderer.java:164) at javax.faces.Component.UIComponentBase.encodeEnd(Uicomponentbase.java:920) at javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1863) at org.primefaces.Component.column.Column.renderChildren(Column.java:352) at org.primefaces.Component.datatable.Datatablerenderer.encodeCell(Datatablerenderer.java:1051) at org.primefaces.Component.datatable.Datatablerenderer.encodeRow(Datatablerenderer.java:999) at org.primefaces.Component.datatable.Datatablerenderer.encodeRows(Datatablerenderer.java:907) at org.primefaces.Component.datatable.Datatablerenderer.encodeTbody(Datatablerenderer.java:854) at org.primefaces.Component.datatable.Datatablerenderer.encodeTbody(Datatablerenderer.java:814) at org.primefaces.Component.datatable.Datatablerenderer.encodeRegularTable(Datatablerenderer.java:290) at org.primefaces.Component.datatable.Datatablerenderer.encodeMarkup(Datatablerenderer.java:252) at org.primefaces.Component.datatable.Datatablerenderer.encodeEnd(Datatablerenderer.java:87) at javax.faces.Component.UIComponentBase.encodeEnd(Uicomponentbase.java:920) at javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1863) at javax.faces.render.Renderer.encodeChildren(Renderer.java:176) javax.faces.Component.UIComponentBase.encodeChildren(Uicomponentbase.java:890) at javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1856) at javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) at javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Faceletviewhandlingstrategy.java:458) at com.sun.faces.application.view.MultiViewHandler.renderView(Multiviewhandler.java:134) at javax.faces.application.ViewHandlerWrapper.renderView(Viewhandlerwrapper.java:337) at javax.faces.application.ViewHandlerWrapper.renderView(Viewhandlerwrapper.java:337) with.sun.faces.lifecycle.Renderresponsephase.execute(Renderresponsephase.java:120) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.Lifecycleimpl.render(Lifecycleimpl.java:219) at javax.faces.webapp.FacesServlet.service(Facesservlet.java:659) at org.apache.Catalina.core.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:231) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:166) at org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:52) at org.apache.Catalina.core.Applicationfilterchain.internalDoFilter(Applicationfilterchain.java:193) at org.apache.Catalina.core.Applicationfilterchain.doFilter(Applicationfilterchain.java:166) at org.apache.Catalina.core.Standardwrappervalve.invoke(Standardwrappervalve.java:198) at org.apache.Catalina.core.Standardcontextvalve.invoke(Standardcontextvalve.java:96) at org.apache.Catalina.authenticator.Authenticatorbase.invoke(Authenticatorbase.java:478) at org.apache.Catalina.core.Standardhostvalve.invoke(Standardhostvalve.java:140) at org.apache.Catalina.valves.Errorreportvalve.invoke(Errorreportvalve.java:80) at org.apache.Catalina.valves.Abstractaccesslogvalve.invoke(Abstractaccesslogvalve.java:624) at org.apache.Catalina.core.Standardenginevalve.invoke(Standardenginevalve.java:87) at org.apache.Catalina.connector.Coyoteadapter.service(Coyoteadapter.java:342) at org.apache.Coyote.http11.Http11processor.service(Http11processor.java:799) at org.apache.Coyote.AbstractProcessorLight.process(Abstractprocessorlight.java:66) at org.apache.Coyote.Abstractprotocol$Connectionhandler.process(Abstractprotocol.java:861) at org.apache.Tomcat.util.net.Nioendpoint$Socketprocessor.doRun(Nioendpoint.java:1455) at org.apache.Tomcat.util.net.SocketProcessorBase.run(Socketprocessorbase.java:49) at java.util.Concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.Concurrent.Threadpoolexecutor$Worker.run(Unknown Source) at org.apache.Tomcat.util.threads.Taskthread$Wrappingrunnable.run(Taskthread.java:61) at java.lang.Thread.run(Unknown Source)

This is my page I’m having trouble getting the name of the student from the bank, because the name of the teacher is coming normal.

Gestaoprojetos.xhtml

<!DOCTYPE html>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
 	xmlns:h="http://xmlns.jcp.org/jsf/html"
 	xmlns:f="http://xmlns.jcp.org/jsf/core"
 	xmlns:p="http://primefaces.org/ui"
 	xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
 	template="/WEB-INF/template/Layout.xhtml">
 	
<ui:define name="titulo">
	<title>Gestão Projetos</title>
</ui:define>
<ui:define name="conteudo">

	<f:metadata>
		<f:viewAction action="#{gestaoProjetosBean.todosProjetos}" />
	</f:metadata>

<p:dataTable id="projetosDataTable" value="#{gestaoProjetosBean.listaProjetos}"
			var="projeto" emptyMessage="Nenhuma informação a ser exibida"
			paginator="true" rows="10" paginatorPosition="bottom"
			selectionMode="single" selection="#{gestaoProjetosBean.projeto}" rowKey="#{projeto.id}">
			
			<p:ajax event="rowSelect" update="frm:toolbar" />
			
			<p:ajax event="rowUnselect" update="frm:toolbar" />
			
			<p:column headerText="Título" sortBy="#{projeto.titulo}">
				<h:outputText value="#{projeto.titulo}" />
			</p:column>
			<!--AQUI O PROFESSOR VEM NORMAL -->
			<p:column headerText="Professor responsável">
				<h:outputText value="#{projeto.professor.usuario.nome}" />
			</p:column>
			<!-- AQUI  É O PROBLEMA QUE NÃO VEM O NOME ALUNO -->
			<p:column headerText="Aluno" >
				<h:outputText value="#{projeto.aluno.usuario.nome}" />
			</p:column>
			 
		</p:dataTable>
</ui:composition>

Gestaoprojetosbean.java(My bean)

@Named
@ViewScoped
public class GestaoProjetosBean implements Serializable {

private static final long serialVersionUID = 1L;

    @Inject
    private Projetos projetos;

    @Inject
    private FacesMessages messages;

    @Inject
    private CadastroProjetoService cadastroProjetoService;

    private List<Projeto> listaProjetos;

    private String termoPesquisa;

    private Projeto projeto;


    public void prepararNovoProjeto() {
        projeto = new Projeto();
        this.projeto.setUsuario(new Usuario());
        //this.projeto.setAluno(new Aluno());
        this.projeto.setProfessor(new Professor());

    }

    public void prepararEdicao() {

    }

    public void salvar() {
        cadastroProjetoService.salvar(projeto);

        atualizarRegistros();

        messages.info("Projeto salvo com sucesso!");

        RequestContext.getCurrentInstance().update(Arrays.asList(
                "frm:monografiasDataTable", "frm:messages"));
    }

    public void excluir() {
        cadastroProjetoService.excluir(projeto);

        projeto = null;

        atualizarRegistros();

        messages.info("Projeto excluída com sucesso!");
    }

    public void pesquisar() {
        listaProjetos = projetos.pesquisar(termoPesquisa);

        if (listaProjetos.isEmpty()) {
            messages.info("Sua consulta não retornou registros.");
        }
    }

    public void todosProjetos() {
        listaProjetos = projetos.todas();
    }

    private void atualizarRegistros() {
        if (jaHouvePesquisa()) {
            pesquisar();
        } else {
            todosProjetos();
        }
    }

    private boolean jaHouvePesquisa() {
        return termoPesquisa != null && !"".equals(termoPesquisa);
    }

    public List<Projeto> getListaProjetos() {
        return listaProjetos;
    }

    public String getTermoPesquisa() {
        return termoPesquisa;
    }

    public void setTermoPesquisa(String termoPesquisa) {
        this.termoPesquisa = termoPesquisa;
    }

    public Projeto getProjeto() {
        return projeto;
    }

    public void setProjeto(Projeto projeto) {
        this.projeto = projeto;
    }

    public boolean isProjetoSeleciona() {
        return projeto != null && projeto.getId() != null;
    }
   }

Java student.

@Entity
@Table(name="aluno")
public class Aluno implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "usuario_id", nullable = false)
private Usuario usuario;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public Usuario getUsuario() {
    return usuario;
}

public void setUsuario(Usuario usuario) {
    this.usuario = usuario;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Aluno other = (Aluno) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

@Override
public String toString() {
    return "Aluno [id=" + id + "]";
}


}

Java user.

@Entity
@Table(name="usuario")
public class Usuario implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty
@Column(nullable = false, length = 40)
private String nome;

@NotEmpty
@Email
@Column(nullable = false, length = 40)
private String email;

@NotNull
@Column(nullable = false, length = 8)
private Long matricula;

@NotEmpty
@Column(nullable = false, length = 8)
private String senha;

@Column(name = "ultimo_acessso")
@Temporal(TemporalType.DATE)
private Date ultimoAcesso;

@Transient
private Professor professor;
@Transient
private List <Aluno> aluno;

public Usuario() {
    super();

}

public Usuario(Long matricula, String senha) {
    super();
    this.matricula = matricula;
    this.senha = senha;

}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getSenha() {
    return senha;
}

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

public Date getUltimoAcesso() {
    return ultimoAcesso;
}

public void setUltimoAcesso(Date ultimoAcesso) {
    this.ultimoAcesso = ultimoAcesso;
}

public Long getMatricula() {
    return matricula;
}

public void setMatricula(Long matricula) {
    this.matricula = matricula;
}

public String getNome() {
    return nome;
}

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

public String getEmail() {
    return email;
}

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

public Professor getProfessor() {
    return professor;
}

public void setProfessor(Professor professor) {
    this.professor = professor;
}

public List<Aluno> getAluno() {
    return aluno;
}

public void setAluno(List<Aluno> aluno) {
    this.aluno = aluno;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Usuario other = (Usuario) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

@Override
public String toString() {
    return "Usuario [id=" + id + "]";
}

}

Java project.

@Entity
@Table(name = "projeto")
public class Projeto implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotEmpty
@Column(nullable = false, length = 120)
private String titulo;

@NotEmpty
@Column(nullable = false)
private String descricao;

@NotNull
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "professor_id", nullable = false)
private Professor professor;


@ManyToMany
@JoinTable(name="projeto_aluno", joinColumns=
{@JoinColumn(name="projeto_id")}, inverseJoinColumns=
{@JoinColumn(name="aluno_id")})
private List <Aluno> aluno;

@Transient
private Usuario usuario;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getTitulo() {
    return titulo;
}

public void setTitulo(String titulo) {
    this.titulo = titulo;
}

public String getDescricao() {
    return descricao;
}

public void setDescricao(String descricao) {
    this.descricao = descricao;
}

public Professor getProfessor() {
    return professor;
}

public void setProfessor(Professor professor) {
    this.professor = professor;
}

public List<Aluno> getAluno() {
    return aluno;
}

public void setAluno(List<Aluno> aluno) {
    this.aluno = aluno;
}

public Usuario getUsuario() {
    return usuario;
}

public void setUsuario(Usuario usuario) {
    this.usuario = usuario;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Projeto other = (Projeto) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

@Override
public String toString() {
    return "Projeto [id=" + id + "]";
}
}
  • What is your intention? The error is exactly what you said, there is no attribute Aluno in class Projeto. There is a List of Aluno.

  • You want to show all the students in this project?

  • Opa Henrique blz! I want to show in the Datatable line the title, teacher and student who are related to this project, so I do not want a list of students but the student related to this project

  • but you have a collection, a list of students, and not just a.

  • Yes true, but excuse my question, I’m new to development. In @manytomany mapping I could only do with the 'student' attribute as List, I couldn’t leave it as the attribute of the guy Aluno, it has to be private Aluno aluno?

  • Dude, you have to study it in databases and jpa/Hibernate. Your problem lies in the basis of the technologies you are using. Read about database relationships and then see how jpa provides those relationships with those annotations @OneTomany, @ManyToMany........

  • Valeu Henrique!

Show 2 more comments

1 answer

0


I managed to solve my problem. I’m sorry that I’m not aware of this stupid beginner’s question that the problem was pretty simple to solve, but you’d already killed yourself looking for it and you didn’t solve it, so I posted it here. I’ll put it here to help some newbie like me who falls into this trouble.

I decided to modify mine <h:outputText> as follows:

        <p:column headerText="Aluno" >
            <h:outputText value="#{projeto.alunos[0].usuario.nome}" />
        </p:column>

I put the [0]on the property alunos and he received the nome of aluno that I was unable to catch.I think the mistake was because he was getting a list of alunos, but I just wanted that aluno which was related to projeto for id.

Who wants to know more about, this post helped me: https://stackoverflow.com/questions/19629067/showing-hibernate-jpa-results-in-jsf-datatable-causes-java-lang-numberformatexc

Browser other questions tagged

You are not signed in. Login or sign up in order to post.