java.lang.Nullpointerexception on chat system

Asked

Viewed 1,314 times

0

I am doing a chat project Helpdesk with JSF 2.0 and Primefaces, but an error is generated when I try to connect the Attendant or user in chat.

In atendente.xhtml and index.xhtml has a form that sends the information to a AtendenteBean.java and UsuarioBean.java, respectively.

Attendant.jsp:

<p:panel header="Login do Atendente" rendered="#{not atendenteMB.autenticado}">
         <h:outputLabel for="txtNome" value="Login:"/>
         <br/>

         <h:inputText id="txtNome" value="#{atendenteMB.atendente.login}"/>
         <br/>

         <h:outputLabel for="txtSenha" value="Senha:"/>
         <br/>

         <h:inputSecret id="txtSenha" value="#{atendenteMB.atendente.senha}"/>
         <br/>
         <h:commandButton action="#{atendenteMB.signIn}" value="Entrar"/>
         <br/>

       </p:panel>

Atendentebean.java:

@ManagedBean(name="atendenteMB")

@SessionScoped
public class AtendenteBean implements Serializable{

public AtendenteBean(){
}

private static final long serialVersionUID = 1L;

@ManagedProperty(value="#{localizadorMB}")
private LocalizadorBean gerenciarLocalizador;

@ManagedProperty(value="#{chatMB}")
private ChatBean chat;

private Atendente atendente = new Atendente();
private boolean autenticado;

public void signIn(){
    if(atendente.getLogin().equals(atendente.getSenha())){
        gerenciarLocalizador.getGerenciador().addAtendente(atendente);
        setAutenticado(true);
    }
    else{
        FacesMessage msgm = new FacesMessage("Login ou Senha inválidos.");
        FacesContext.getCurrentInstance().addMessage(null, msgm);
    }

}

Error generated when I click the Send button.

HTTP Status 500 - java.lang.NullPointerException

type Exception report

message
---
java.lang.NullPointerException

description
---
The server encountered an internal error that prevented it from fulfilling this request.

exception 
---
javax.servlet.ServletException: java.lang.NullPointerException
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)



root cause 
---
javax.faces.el.EvaluationException: java.lang.NullPointerException
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpress    ionAdapter.java:101)
        com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
        com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)



root cause
---

java.lang.NullPointerException
    managedbean.AtendenteBean.signIn(AtendenteBean.java:34)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
        javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpress    ionAdapter.java:87)
        com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    javax.faces.component.UICommand.broadcast(UICommand.java:315)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
        com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)



note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.

If you need more details, just comment.

  • What’s in the line below?: managedbean.AtendonBean.signIn(Atendentebean.java:34)

  • I edited and left the relevant code parts to the question.

  • 2

    The question is, do you have an error pointing to line 34 of Atendentebean. What is the code of that line? And there’s the problem.

  • This one below: public void signIn(){ if(attendant.getLogin().equals(attendant.getSenha())){ managereLocator.getGerentiater(). addAtendente(attendant ); setAutenticado(true); } Else{ Facesmessage msgm = new Facesmessage("Invalid login or password."); Facescontext.getCurrentInstance(). addMessage(null, msgm); } }

  • Again, what is on line 34? Is the if? The whole method is in the code above. You need to know what is on line 34 only.

  • Line 34 starts at: managerLocator.getGerentiater(). addAtendente(attendant); in the code field I put this method.

  • 2

    Beauty. Now do a DEBUG and see who’s null there. There’s a lot of chained object there.

  • I did not intend to debug but it stopped on line 34 and reported the error Nullpointer and on the top line is selected gray color the 'getSette();'.

  • How do I see who is Null? , getSenha() was only selected from gray because I had clicked on it, it was bad.

  • @Luiz which IDE are you using? Eclipse, Netbeans?

  • Problem solved with debug, thanks to Math for helping in another topic and @uaiHebert for the suggestion. The variable managementLocator was Null, because I had not instantiated it in my class and the constructor of the object tbm did not initialize correctly.

Show 6 more comments

1 answer

1


Debug for what I want you..

But looking over, there are 3 lines within the signIn() method that may be referencing null references:

1 - attendant.getLogin(). equals(...)
2 - managementLocator.getGerentiater(). addAtendon(attendant)
3 - Facescontext.getCurrentInstance(). addMessage(null, msgm)

If getLogin(), getGerentiater() or getCurrentInstance() return a null reference, it is not possible to access methods or properties of the object, since it is not where it should be

You can solve this in two ways: running a debug and checking the return of each of these 3 methods above, or what is most indicated; allot in local variables within the scope of the function signIn and check for the nullity of the object before accessing its members nested as you did.

Login l = atendente.getLogin();
if(l == null) {
 ... // imprime no console.. fonte do bug
  return; // retorna abruptamente
}

// ok, temos certeza que "f" existe
if (l.equals(...)) {...}

Gerenciador g = gerenciarLocalizador.getGerenciador();
if(g == null) {
 // imprime no console.. fonte do bug
 return; // retorna abruptamente
}

// ok, agora temos certeza que "g" existe
g.addAtendente(atendente);

FacesContext context = FacesContext.getCurrentInstance()

if(context != null) { ... }

If after you want to detect which of these turns null and correct the error (missing to be created somewhere else), you can return your code as it was nested if you want, but provided that the objects are always guaranteed to have been instantiated before (although it is not good practice)

  • Eh, this sure is good practice for discovering the null element. I didn’t think about it. But pq is not good practice instantiating objects?

  • 1

    What is not very advisable, exactly for going back to the types of error you encountered, is to nest the dereferences to the objects in the form "x.geta(). Dob()" when "geta()" returns a compound object/class instead of a simple value as an integer.. The ideal is to store in various locations and reuse this local variable within the scope. The only exception is when returning Singleton objects in static methods as in the case of "Facescontext.getCurrentInstance()" since it is assumed that within the static method the object is instated if null, having no danger of returning 'null''

  • ata, the correct would then nest variables instead of methods, could even test them in Try.. catch to treat the nullPointer exception... The nesting would be if (l.equals(s)) {...}, being l of getLoguin() and s of getSenha().

  • the "attendant.getSenha()" has no problem, it would even be indicated to use direct in this case for code readability issues.. the "attendant.getLogin(). equals()" could also pass, since it is understood that it is a string and should not be null under any circumstances.. already the "managementLocator.getGerentiater(). addAtendor(attendant)" may be a problem, but it could also be used only if "getGerentiater()" were static, which is not the case as I saw in the code, in this case yes, allocates it to a local variable, and then executes "addAtendent()" will even help you debug.

  • Thanks for the help and tips!

Browser other questions tagged

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