Erro ao logar no sistema (login)

3 respostas
fernandoh.computacao

Pessoal estou com um erro ao tentar efetuar um login, ñ to conseguindo, ja segui alguns tutoriais, mas ñ descobri o pq acontece…

Eu tenho minha Classe Usuario.java (está contida no pacote entity)

package br.unemat.bbg.entity;

import static br.unemat.bbg.util.Crypt.*;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name = "USUARIO")
public class Usuario implements Serializable {

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String nome;
    private String login;
    private String senha;
    private String status;
    private char altera;
    private char bloqueado;
    private TipoUsuario tipoUsuario;

    public Usuario() {
    }

    @Column(name = "USUARIO_ALTERA", nullable = false, length = 1)
    public char getAltera() {
        return altera;
    }

    public void setAltera(char altera) {
        this.altera = altera;
    }

    @Column(name = "USUARIO_BLOQ", nullable = false, length = 1)
    public char getBloqueado() {
        return bloqueado;
    }

    public void setBloqueado(char bloqueado) {
        this.bloqueado = bloqueado;
    }

    @Id
    @GeneratedValue
    @Column(name = "USUARIO_ID", nullable = false)
    public Integer getId() {
        return id;
    }

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

    @Column(name = "USUARIO_LOGIN", nullable = false, length = 20)
    public String getLogin() {
        return login.toUpperCase();
    }

    public void setLogin(String login) {
        this.login = login.toUpperCase();
    }

    @Column(name = "USUARIO_NOME", nullable = false, length = 40)
    public String getNome() {
        return nome;
    }

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

    @Column(name = "USUARIO_SENHA", nullable = false, length = 10)
    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        try {
            String novaSenha = doCrypt(senha, CRYPT_MD5);
            this.senha = novaSenha.substring(0, 10);
        } catch (Exception ex) {
            this.senha = (senha);
            Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Column(name = "USUARIO_STATUS", columnDefinition = "CHAR(1) DEFAULT 1")
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public TipoUsuario getTipoUsuario() {
        return tipoUsuario;
    }

    public void setTipoUsuario(TipoUsuario tipoUsuario) {
        this.tipoUsuario = tipoUsuario;
    }

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

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 71 * hash + (this.id != null ? this.id.hashCode() : 0);
        return hash;
    }
}

LoginBean.java

package br.unemat.bbg.bean;

import br.unemat.bbg.util.HibernateUtil;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * 
 * @author Fernando
 */
@ManagedBean()
@SessionScoped
public class LoginBean {

	private Session session;
	private String login;
	private String senha;
	protected EntityManager entityManager;

	public String getSenha() {
		return senha;
	}

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

	public String getUsuario() {
		return login;
	}

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

	public LoginBean() {
	}

	public String efetuarLogin() {
		
		System.out.println("Para teste ****      ");
		System.out.println("************ Login: " + login);
		System.out.println("************ Senha: " + senha);

		StringBuffer sb = new StringBuffer();
		sb.append("FROM Usuario u");
		sb.append("WHERE u.login = :pLogin");
		sb.append("AND u.senha = :pSenha");	
		

		session = HibernateUtil.getInstance();
		Transaction tx = null;

		try {
			tx = session.beginTransaction();
			Query query = entityManager.createQuery(sb.toString());
			query.setParameter("pLogin", login);
			query.setParameter("pSenha", senha);
			
			tx.commit();

			boolean encontrado = !query.getResultList().isEmpty();

			if (encontrado) {
				return "/pages/home.jsf";
			} else {
				login = null;
				senha = null;
				return "/login.jsf";
			}
		} catch (HibernateException e) {
			tx.rollback();
			return null;
		} finally {
			session.close();
		}
	}
}

Login.xhtml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html>

<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.prime.com.tr/ui">


<h:head>
	<link href="css/estilo.css" rel="stylesheet" type="text/css"></link>
	<title>Estágio Supervisionado</title>
</h:head>

<h:body style="background-image: url('/images/fundo_site.jpg')">
	<div id="main">

		<div id="topo">
			<img src="#{msg['sistema.label.imageLogo']}"
				alt="Unemat - Computação" width="250" height="100" />
			<h1>Estágio Supervisionado</h1>
			<h2>
				<h:outputText value="#{msg['sistema.label.unemat']}" />
			</h2>
		</div>

		<f:view>
			<div align="center">
				<br />
				<br />
				<br />
				<br />
				<br />
				<br />
				<br />
				<br />

				<h:form>
					<p:panel id="panelLogin" style="width: 400px">

						<f:facet name="header">
							<h:outputText value="Área de Login" />
						</f:facet>
						<br />
						<h:panelGrid columns="3">


							<h:panelGroup>
								<h:outputLabel id="lblUsuario" value="Usuário" for="txtUsuario"
									style="text-align: right" />
							</h:panelGroup>
							<h:panelGroup>
								<h:inputText id="txtUsuario" value="#{loginBean.usuario}"
									required="true" requiredMessage="Campo Obrigatório!" />
							</h:panelGroup>
							<h:panelGroup>
								<p:message for="txtUsuario" />
							</h:panelGroup>

							<h:panelGroup>
								<h:outputLabel id="lblSenha" value="Senha" for="txtSenha"
									style="text-align: right" />
							</h:panelGroup>
							<h:panelGroup>
								<h:inputSecret id="txtSenha" value="#{loginBean.senha}"
									required="true" requiredMessage="Campo Obrigatório!" />
							</h:panelGroup>
							<h:panelGroup>
								<p:message for="txtSenha" />
							</h:panelGroup>

						</h:panelGrid>

						<br />
						<p:commandButton id="btnEntrar" action="#{loginBean.efetuarLogin}"
							value="Entrar" update="panelLogin" />
						<p:commandButton id="btnLimpar" value="Limpar" type="reset" />
						<br />
					</p:panel>

				</h:form>
			</div>
		</f:view>

		<p:dock>
			<p:menuitem value="Home" icon="/images/home.png" url="/login.jsf"></p:menuitem>
			<p:menuitem value="Email" icon="/images/email.png" url="#" />
			<p:menuitem value="Link" icon="/images/link.png" url="#" />
			<p:menuitem value="Histórico" icon="/images/history.png" url="#" />
			<p:menuitem value="Equipe" icon="/images/adm.png" url="#" />
			<p:menuitem value="Dúvidas" icon="/images/duvidas.png" url="#" />
		</p:dock>

	</div>
</h:body>
</html>

ERRO propriamente dito

11/08/2011 01:31:20 com.sun.faces.application.ActionListenerImpl processAction
GRAVE: java.lang.NullPointerException
javax.faces.el.EvaluationException: java.lang.NullPointerException
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.NullPointerException
	at br.unemat.bbg.bean.LoginBean.efetuarLogin(LoginBean.java:61)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
	... 24 more
11/08/2011 01:31:20 com.sun.faces.lifecycle.InvokeApplicationPhase execute
AVISO: #{loginBean.efetuarLogin}: java.lang.NullPointerException
javax.faces.FacesException: #{loginBean.efetuarLogin}: java.lang.NullPointerException
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:662)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 23 more
Caused by: java.lang.NullPointerException
	at br.unemat.bbg.bean.LoginBean.efetuarLogin(LoginBean.java:61)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
	... 24 more
javax.faces.FacesException: #{loginBean.efetuarLogin}: java.lang.NullPointerException
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:662)
Caused by: javax.faces.FacesException: #{loginBean.efetuarLogin}: java.lang.NullPointerException
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	... 19 more
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
	... 23 more
Caused by: java.lang.NullPointerException
	at br.unemat.bbg.bean.LoginBean.efetuarLogin(LoginBean.java:61)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
	... 24 more

Oq estou fazendo errado? alguem pode me ajudar

3 Respostas

balrog

nullpointer exception linha 61
seu EM esta null

fernandoh.computacao

sim, mas ñ esta correto meu MB?

balrog

tente anotar seu EM com @PersistenceContext

Criado 11 de agosto de 2011
Ultima resposta 11 de ago. de 2011
Respostas 3
Participantes 2