Target Unreachable, Identifier 'usuarios' resolved to null

Asked

Viewed 2,562 times

0

My bean:

package com.cliente.Bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.omnifaces.util.Messages;

import com.sistema.dao.PessoaDAO;
import com.sistema.dao.UsuarioDAO;

import com.sistema.domain.Pessoa;
import com.sistema.domain.Usuario;

@SuppressWarnings("serial")
@ManagedBean
@ViewScoped
public class UsuarioBean implements Serializable {

    private Usuario usuario;
    private List<Usuario> usuarios;
    private List<Pessoa> pessoas;

    public Usuario getUsuario() {
        return usuario;
    }

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

    public List<Usuario> getUsuarios() {
        return usuarios;
    }

    public void setUsuarios(List<Usuario> usuarios) {
        this.usuarios = usuarios;
    }

    public List<Pessoa> getPessoas() {
        return pessoas;
    }

    public void setPessoas(List<Pessoa> pessoas) {
        this.pessoas = pessoas;
    }

    public void novo() {
        try {

            usuario = new Usuario();

            PessoaDAO pessoaDAO = new PessoaDAO();
            pessoas = pessoaDAO.listar("nomeUsuario");

            pessoas = new ArrayList<Pessoa>();

        } catch (RuntimeException erro) {
            Messages.addGlobalError("Ocorreu um erro ao tentar listar as baladas");
            erro.printStackTrace();
        }
    }

    public void salvar() {
        try {

            UsuarioDAO usuarioDAO = new UsuarioDAO();

            usuarioDAO.merge(usuario);

            novo();
            usuario = new Usuario();

            PessoaDAO pessoaDAO = new PessoaDAO();
            pessoas = pessoaDAO.listar();

            usuarios = usuarioDAO.listar();

            Messages.addGlobalInfo("Cliente Salvo Com sucesso");
        } catch (RuntimeException erro) {
            Messages.addFlashGlobalError("Ocorreu um erro ao tentar salvar o cliente");
            erro.printStackTrace();
        }
    }

}

My XHTML:

<?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"
    xmlns:ui="http://java.sun.com/jsf/facelets">



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

<h:outputStylesheet library="css" name="estilo.css" />
    <h:outputStylesheet library="js" name="scripts.js" />



</h:head>
<h:body>
<p:growl id="mensagem"/>
<h:form id="formListagem">


<p:panel header="Lista de Usuários">
<p:dataTable id="tabela" emptyMessage="Nehum registro encontrado" paginator="true">
<f:facet name="header">
<p:commandButton value="Novo" oncomplete="PF('dialogo').show();"
actionListener=":formCadastro:pnCadastro"/>
</f:facet>



<p:column headerText="Codigo" value="#{usuario.codigo}">
</p:column>

<p:column headerText="Ativo" value="#{usuario.ativo}">
</p:column>

<p:column headerText="Senha" value="#{usuario.senha}">
</p:column>


<p:column headerText="Tipo" value="#{usuario.tipo}">
</p:column>


<p:column headerText="Opções">



</p:column>
</p:dataTable>
</p:panel>
</h:form>

<p:dialog header="Usuários - Cadastro" widgetVar="dialogo"
draggable="false" resizable="false" modal="true" closable="false">
<h:form id="formCadastro">
<h:panelGrid columns="2" id="pnCadastro">


    <p:outputLabel for="pessoa" value="Pessoa:" />

                <p:selectOneMenu id="pessoa" filter="true"
                    value="#{usuarioBean.usuario.pessoa}" required="true"
                    requiredMessage="O campo 'Pessoa' é obrigatório"
                    converter="omnifaces.SelectItemsConverter">

                    <f:selectItem noSelectionOption="true"
                        itemLabel="Selecione uma pessoa" />

                    <f:selectItems value="#{pessoaBean.pessoas}" var="pessoa"
                        itemValue="#{pessoa}" itemLabel="#{pessoa.nomeUsuario} " />
                </p:selectOneMenu>



                <p:outputLabel for="senha" value="Senha:" />

                <p:password id="senha" maxlength="8" size="10"
                    value="#{usuarios.senha}" required="true"
                    requiredMessage="O campo 'Senha' é obrigatório"
                    validatorMessage="Informe uma senha de 6 a 8 caracteres">
                    <f:validateLength minimum="6" maximum="8" />
                </p:password>




                <p:outputLabel for="tipo" value="Tipo:" />
                <p:selectOneRadio id="tipo" value="#{usuarioBean.usuario.tipo}"
                    required="true" requiredMessage="O campo 'Tipo' ´obrigatório">
                    <f:selectItem itemValue="A" itemLabel="Administrador" />
                    <f:selectItem itemValue="G" itemLabel="Gerente" />
                    <f:selectItem itemValue="U" itemLabel="Usuario" />
                </p:selectOneRadio>

                <p:outputLabel for="ativo" value="Ativo:" />
                <p:selectBooleanCheckbox id="ativo"
                    value="#{usuarioBean.usuario.ativo}" required="true"
                    requiredMessage="O campo 'Ativo' é obrigatório" />

</h:panelGrid>



<h:panelGrid columns="2">
<p:commandButton value="Salvar" actionListener="#{usuarioBean.salvar()}" update=":mensagem :formCadastro:pnCadastro :formListagem:tabela"/>
<p:commandButton value="Fechar" oncomplete="PF('dialogo').hide();"/>

</h:panelGrid>
</h:form>
</p:dialog>
</h:body>
</html>

Tomcat error

jan 05, 2017 4:40:43 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.el.PropertyNotFoundException: /pages/usuario.xhtml @85,63 value="#{usuarios.senha}": Target Unreachable, identifier 'usuarios' resolved to null
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
    at org.primefaces.util.ComponentUtils.getConverter(ComponentUtils.java:146)
    at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:175)
    at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1045)
    at javax.faces.component.UIInput.validate(UIInput.java:975)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIForm.processValidators(UIForm.java:253)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at org.primefaces.component.dialog.Dialog.processValidators(Dialog.java:423)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    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)
Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'usuarios' resolved to null
    at org.apache.el.parser.AstValue.getTarget(AstValue.java:74)
    at org.apache.el.parser.AstValue.getType(AstValue.java:58)
    at org.apache.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:168)
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
    ... 38 more

My class of users:

package com.sistema.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

@SuppressWarnings("serial")
@Entity
public class Usuario extends GenericDomain {

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

    @Column(nullable = false)
    private Character tipo;

    @Column(nullable = false)
    private Boolean ativo;


    @ManyToOne
    @JoinColumn(nullable = false)
    private Pessoa pessoa;






    @ManyToOne
    public Pessoa getPessoa() {
        return pessoa;
    }

    @ManyToOne
    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

    public String getSenha() {
        return senha;
    }

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

    public Character getTipo() {
        return tipo;
    }

    public void setTipo(Character tipo) {
        this.tipo = tipo;
    }

    public Boolean getAtivo() {
        return ativo;
    }

    public void setAtivo(Boolean ativo) {
        this.ativo = ativo;
    }


}

On XHTML, I’ve tried switching #{usuarios.senha} for #{usuario.senha} and for #{usuarioBean.usuario.senha} - All three forms generate the same error.

  • In that first datatable it did not have to have a value and var?

1 answer

1

Your mistake is here:

                <p:password id="senha" maxlength="8" size="10"
                    value="#{usuarios.senha}" required="true"
                    requiredMessage="O campo 'Senha' é obrigatório"
                    validatorMessage="Informe uma senha de 6 a 8 caracteres">
                    <f:validateLength minimum="6" maximum="8" />
                </p:password>

Note the value="#{usuarios.senha}" - See that you used usuarios plural, and not usuario in the singular.

Also, nowhere are you setting the value of usuario, usuarios or usuarioBean.usuario - all of them are null at this point in the program. So trying to use any of them will give this exception, which in practice, is almost the same thing as a NullPointerException. A possible solution for this would be to put in your bean the following:

    private String senha;

    public String getSenha() {
        return senha == null ? "" : senha;
    }

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

And then, on XHTML, you use value="#{usuarioBean.senha}".

Hence, within your method salvar, you put a usuario.setSenha(senha). Do this with all fields to be saved.

I also recommend that you read that my other answer. There, I explain why to use the entity Beans outside the controller (thing you are doing while using them in XHTML and storing them in Managed bean) is not a very good idea. Instead, store in Managed bean and traffic to JSF, only Dtos and other simple data such as strings.

  • I just tested with user.password , user Ean.usuario.password all return the same error. , --an 05, 2017 5:10:22 PM com.sun.faces.context.Ajaxexceptionhandlerimpl handlePartialResponseError GRAVE: javax.el.Propertynotfoundexception: /pages/usuario.xhtml @85,63 value="#{usuarioBean.usuario.password}": Target Unreachable, 'usuario' returned null at com.sun.faces.facelets.el.TagValueExpression.getType(Tagvalueexpression.java:100...

  • @Brunexx Strange, because on line 41, you use <p:column headerText="Senha" value="#{usuario.senha}"> and there is no mistake. Because then the mistake would be in 82-85?

  • So I don’t know what’s going on in this class, which is having these problems the other ones are working normally

  • I deleted the users.password and tested the type I gave the same thing here : CODE ----- <p:outputLabel for="type" value="Type:" /> <p:selectOneRadio id="type" value="#{usuarioBean.usuario.type}" required="true" requiredMessage="The 'Type' field is required"> <f:selectItem itemValue="A" itemLabel="Administrator" /> <f:selectItem itemValue="G" itemLabel="Manager" /> <f:selectItem itemValue="U" itemLabel="User" /> </p:selectOneRadio>

  • Erro tom cat : jan 05, 2017 5:22:30 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError&#xA;GRAVE: javax.el.PropertyNotFoundException: /pages/usuario.xhtml @86,68 value="#{usuarioBean.usuario.tipo}": Target Unreachable, 'usuario' returned null&#xA; at com.sun.faces.facelets.el.TagValueExpression.getType(Tagvalueexpression.java:100)

  • @Brunexx Reply edited.

Show 1 more comment

Browser other questions tagged

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