Tela de Login - Servlet e tomcat

12 respostas
E

Boa tarde!!!

Gente estou a mais de 2 semanas tentando fazer uma tela de login. Vi vários jeitos de se fazer mas nenhum funcionou =(

Como estou começando escolhi algo que achei que fosse mais fácil, usando o raciocinio:
O usuário digita os valores (login e senha) em um jsp.
A servlet pega os valores
(ate ai td bem…)
A servlet passa os valores para uma classe e esta verifica os dados.
A classe retorna true ou false para a servlet.
A servet redireciona para a pag principal do sistema

CLASS DE CONEXAO

package portal;

import java.sql.*;

public class ConexaoMysql {
	Connection conexao = null;
	
	ConexaoMysql() {
		String urlCon = "jdbc:mysql://localhost/portalcco?user=root&password=ellen291";
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conexao = DriverManager.getConnection(urlCon);
		} catch(Exception erro) {
			System.out.println("Erro ocorrido: n" + erro);
		}
	}
	
	Connection getConnection(){
		return conexao;
	}
	
	void closeConnection(){
		try {
			conexao.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

SERVLT DE ‘CONTROLE’

package portal;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			PrintWriter out = response.getWriter();
			String login = request.getParameter("user");
			String senha = request.getParameter("senha");
			
			Verifica fazLogin = new Verifica();    //conecta a classe
			boolean resultado = fazLogin.Ver(login, senha);//passa o parametro e recebe a resposta
			if (resultado = true) {
				out.println("Você esta logado!!!" + resultado);//exibe resultado
			} else {
				out.println("Você não existe" + resultado);
			}
	}

}

CLASSE DE MODEL

package portal;

import java.sql.ResultSet;
import java.sql.Statement;
import portal.ConexaoMysql;

public class Verifica {
	private ConexaoMysql conexaoMysql;

	Verifica() {
		//ConexaoMysql conexaoMysql;
	}
	
	public boolean Ver(String login, String senha) {
		conexaoMysql = new ConexaoMysql();
		
		Statement state = null;
		ResultSet rs = null;

		try {
			state = conexaoMysql.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
			rs = state.executeQuery("Select * from users where matricula = '" + login + "' and senha = '" + senha +"'");

			/*while(rs.next()) {
				System.out.println("Nome do Cliente: " + rs.getString("matricula") + " Senha: " + rs.getString("senha"));
				System.out.print("----------------------------------------nn");
			}
			if (rs != null) {
				return true;
			} else {
				return false;
			}*/
		} catch(Exception erro) {
			System.out.println("Erro ocorrido: n" + erro);
		} finally {
			conexaoMysql.closeConnection();
		}
		//return true;
		//return false;
		if (rs != null) {
			return true;
		} else {
			return false;
		}
	}

	/*public static void main(String args[]){
		new pag();
	}*/
}

Quem puder me dar uma forcinha ficarei mto grata.

Ah, qndo eu coloco a servlet para somente exibir os dados ditados pelo usuario funciona (o cod esta abaixo) mas qndo faço do jeito acima o tomcat da um erro

package portal;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			PrintWriter out = response.getWriter();
			String login = request.getParameter("user");
			String senha = request.getParameter("senha");
			
			out.println("O usuário é:" + login + " a senha é: " + senha);//exibe resultado

			/*Verifica fazLogin = new Verifica();    //conecta a classe
			boolean resultado = fazLogin.Ver(login, senha);//passa o parametro e recebe a resposta
			if (resultado = true) {
				out.println("Você esta logado!!!" + resultado);//exibe resultado
			} else {
				out.println("Você não existe" + resultado);
			}*/
	}

}

12 Respostas

Neto.Sabio

brother qual é o erro que o Tomcat Aponta ?

rdgms
if (resultado = true)

para

if (resultado == true)

ou

if (resultado)
E

Por favor, sister…rs
Este é o erro:

HTTP Status 500 -


type Exception report

message

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

exception

java.lang.NullPointerException

portal.ConexaoMysql.closeConnection(ConexaoMysql.java:24)

portal.Verifica.Ver(Verifica.java:35)

portal.Login.doPost(Login.java:33)

javax.servlet.http.HttpServlet.service(HttpServlet.java:647)

javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

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


Apache Tomcat/5.5.27

E

[quote=rdgms]if (resultado = true)
para

if (resultado == true)

ou

if (resultado)

Realmente estava errado mas… mesmo assim continua dando o erro acima

E

Li que java.lang.NullPointerException <<< essa exception é do tipo RuntimeException, e ela é lançada apenas em tempo de execução pela máquina virtual. O porque esta acontecendo essa exception é porque você está tentando chamar um método em uma referência nula!

Parece que ela acontece quando chamo o método

finally {
			conexaoMysql.closeConnection();
		}

O METODO que esta na classe ConexaoMysql

void closeConnection(){
		try {
			conexao.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

Fiz um teste e tirei essa parte do código e funcionou. ***

Como faço pra resolver isso? Preciso fechar a conexao!!!

***Funcionou entre “” pois me retornou false quando era para ser true pois todos os dados digitados estao corretos.

Thiago_Luis

Olá, tudo bom?

Faça este teste:

void closeConnection(){ if(conexao!=null){ try { conexao.close(); } catch (SQLException e) { e.printStackTrace(); } }else{ System.out.println("Conexão está nula"); } }
Talvez, antes de vc chamar o método closeConnection(), a conexão já perdeu a referência, por isso da NullPointerException.

Abraço

E

Thiago Luis:
Olá, tudo bom?

Faça este teste:

void closeConnection(){ if(conexao!=null){ try { conexao.close(); } catch (SQLException e) { e.printStackTrace(); } }else{ System.out.println("Conexão está nula"); } }
Talvez, antes de vc chamar o método closeConnection(), a conexão já perdeu a referência, por isso da NullPointerException.

Abraço

Ok… Muito obrigada pela ajuda.
Parece que funcionou pois não dá erro mais no tomcat e nem exibe a msg System.out.println(“Conexão está nula”);
Teoricamente, esta a mesma coisa… nao entendi pq agora funcionou.

Mas ha um problema ainda.
Os dados que o usuário digita para logar no sistema esta com algum erro. Já verifiquei se é case sensitive e os dados estão inseridos no bd e estou digitando corretamente. É nesse trecho do código:

if (rs != null) {
			return true;
		} else {
			return false;
		}

Segue novamente o meu cod da classe Verifica:

package portal;

import java.sql.ResultSet;
import java.sql.Statement;
import portal.ConexaoMysql;

public class Verifica {
	private ConexaoMysql conexaoMysql;

	Verifica() {
		//ConexaoMysql conexaoMysql;
	}
	
	public boolean Ver(String login, String senha) {
		conexaoMysql = new ConexaoMysql();
		
		Statement state = null;
		ResultSet rs = null;

		try {
			state = conexaoMysql.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
			rs = state.executeQuery("Select * from users where matricula = '" + login + "' and senha = '" + senha +"'");

			/*while(rs.next()) {
				System.out.println("Nome do Cliente: " + rs.getString("matricula") + " Senha: " + rs.getString("senha"));
				System.out.print("----------------------------------------nn");
			}
			if (rs != null) {
				return true;
			} else {
				return false;
			}*/
		} catch(Exception erro) {
			System.out.println("Erro ocorrido: n" + erro);
		} finally {
			conexaoMysql.closeConnection();
		}
		//return true;
		//return false;
		if (rs != null) {
			return true;
		} else {
			return false;
		}
	}

	/*public static void main(String args[]){
		new pag();
	}*/
}

=)

Felagund
package portal;

import java.sql.ResultSet;
import java.sql.Statement;
import portal.ConexaoMysql;

public class Verifica {
	private ConexaoMysql conexaoMysql;

	Verifica() {
		//ConexaoMysql conexaoMysql;
	}
	
	public boolean Ver(String login, String senha) {
		conexaoMysql = new ConexaoMysql();
		
		Statement state = null;
		ResultSet rs = null;

		try {
			state = conexaoMysql.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
			rs = state.executeQuery("Select * from users where matricula = '" + login + "' and senha = '" + senha +"'");

			return rs.next();
		} catch(Exception erro) {
			System.out.println("Erro ocorrido: n" + erro);
                        return false;
		} finally {
//sempre fexe os statments, deixar eles abertos vai pesar seu sistema.
if(state != null){
state.close();
}
if(rs != null){
 rs.close();
}
			conexaoMysql.closeConnection();
		}
		//return true;
		//return false;
		/*if (rs != null) {
			return true;
		} else {
			return false;
		}*/
	}

}

Não existe necessidade para retornar o valor fora do try e catch
Assim fica mais simples e mais facil de se usar.

E
Felagund:
package portal;

import java.sql.ResultSet;
import java.sql.Statement;
import portal.ConexaoMysql;

public class Verifica {
	private ConexaoMysql conexaoMysql;

	Verifica() {
		//ConexaoMysql conexaoMysql;
	}
	
	public boolean Ver(String login, String senha) {
		conexaoMysql = new ConexaoMysql();
		
		Statement state = null;
		ResultSet rs = null;

		try {
			state = conexaoMysql.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
			rs = state.executeQuery("Select * from users where matricula = '" + login + "' and senha = '" + senha +"'");

			return rs.next();
		} catch(Exception erro) {
			System.out.println("Erro ocorrido: n" + erro);
                        return false;
		} finally {
//sempre fexe os statments, deixar eles abertos vai pesar seu sistema.
if(state != null){
state.close();
}
if(rs != null){
 rs.close();
}
			conexaoMysql.closeConnection();
		}
		//return true;
		//return false;
		/*if (rs != null) {
			return true;
		} else {
			return false;
		}*/
	}

}

Não existe necessidade para retornar o valor fora do try e catch
Assim fica mais simples e mais facil de se usar.

Olá,

Deu errado da forma como você me sugeriu. Deu esse erro:

HTTP Status 500 -

--------------------------------------------------------------------------------

type Exception report

message

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

exception

javax.servlet.ServletException: Servlet execution threw an exception

root cause

java.lang.Error: Unresolved compilation problem:
Unhandled exception type SQLException

portal.Login.doPost(Login.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)

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

--------------------------------------------------------------------------------

Apache Tomcat/5.5.27

Ah tive que colocar um try/cath.
Ficou assim:

package portal;   
  
import java.sql.ResultSet;   
import java.sql.SQLException;
import java.sql.Statement;   
import portal.ConexaoMysql;   
  
public class Verifica {   
    private ConexaoMysql conexaoMysql;   
  
    Verifica() {   
        //ConexaoMysql conexaoMysql;   
    }   
       
    public boolean Ver(String login, String senha){   
        conexaoMysql = new ConexaoMysql();   
           
        Statement state = null;   
        ResultSet rs = null;   
  
        try {   
            state = conexaoMysql.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);   
            rs = state.executeQuery("Select * from users where matricula = '" + login + "' and senha = '" + senha +"'");   
            //System.out.println (rs);
            return rs.next();   
        } catch(Exception erro) {   
            System.out.println("Erro ocorrido: n" + erro);   
            return false;   
        } finally {   
        	if(state != null){   //fexar os statments
        		try {
					state.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}   
        	}   
        	if(rs != null){   
        		try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}   
			}   
            conexaoMysql.closeConnection();   
        }   
        //return true;   
        //return false;   
        /*if (rs != null) {  
            return true;  
        } else {  
            return false;  
        }*/   
    }   
  
}
Felagund

E não funcionou? a exception que ta dando no servidor é que vc não tratou todas as SQLException, após esses try e catch deveria funcionar, experimente compilar e ver que erros saem

[]'s

E

Felagund:
E não funcionou? a exception que ta dando no servidor é que vc não tratou todas as SQLException, após esses try e catch deveria funcionar, experimente compilar e ver que erros saem

[]'s

Sim os erros sairam mas não esta passando os valores do mesmo jeito…
os valores de login e senha

E

Pessoal,

Resolvi meu problema.
Adivinha o que era???
O conector do mysql… Não tinha o colocado na pasta correta mas concertei meu erro o colocando na basta lib do tomcat, tornando o disponível para qualquer aplicação.

Vlw a ajuda de todos.

Criado 15 de junho de 2009
Ultima resposta 17 de jun. de 2009
Respostas 12
Participantes 5