Pessoal boa noite.
Estou criando um sistema de cadastro via WEB com conexão ao banco de dados MySql.
Minha página já esta pronta e consigo inserir um novo usuário com login e senha sem problemas.
Minha dúvida: Tenho um menu com a opção de consulta e meu botão consulta já está criado, porém não sei como fazer um script para o botão consulta que busque e mostre os dados do usuário já cadastrado no BD.
“Quero consultar o usuário através do cpf”.
Segue abaixo o meu código usuário p/ confirmar que estou fazendo a página.
Preciso apenas de um modelo de script p/ mostrar o resultado da consulta a través do BOTÃO CONSULTAR.
Se alguém puder ajudar?
Atenciosamente
arsoares
Usuario.jsp
[color=red]Document : usuario
Created on : 04/03/2008, 16:27:07
Author : arsoares
–%>
<%@page contentType=“text/html” pageEncoding=“UTF-8”%>
CADASTRO USUÁRIO
RG
CPF
Telefone
Comentários
Desejo receber notificação das novidades.
Tipo de Usuário Administrador Atendente
Login
Senha
********************************************************************** consultaUsuario.jsp
<%–
Document : consultaUsuario
Created on : 15/04/2008, 17:11:25
Author : arsoares
–%>
<%@page contentType=“text/html” pageEncoding=“UTF-8”%>
CONSULTA USUÁRIO
CPF
- Nome
- CPF
********************************************************************** consultaUsuarioServlet.java /** * * @author arsoares */ public class consultaUsuarioServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(); //obtenção do objeto de sessão
UsuarioBean u = null;
String strAcao = request.getParameter("txtAcao");
u = new UsuarioBean (
request.getParameter("nome"),
Integer.parseInt(request.getParameter("rg")),
Integer.parseInt(request.getParameter("cpf")),
Integer.parseInt(request.getParameter("fone")),
request.getParameter("email"),
request.getParameter("login"),
request.getParameter("senha"),
request.getParameter("txtTipoUsuario"),
Boolean.getBoolean("txtLogado"));
UsuarioBean Consultar;
Consultar = UsuarioBD.getUsuario();
session.setAttribute("usuario", u); //sessão referente ao usuário consultado
}
}
UsuarioBean.java
package modelo;
/**
*
-
@author arsoares
*/
public class UsuarioBean {protected String nome;
protected int RG;
protected int cpf;
protected int fone;
protected String email;
protected String login;
protected String senha;
protected String tipoUsuario;
protected boolean logado;
protected boolean verificarUsuario;public UsuarioBean () {
}
public UsuarioBean(String strLogin, String strSenha) {
throw new UnsupportedOperationException(“Not yet implemented”);
}
public UsuarioBean (String strNome, int intRG, int intCpf, int intFone, String strEmail, String strLogin, String strSenha, String strTipoUsuario, Boolean strLogado)
{
nome = strNome;
RG = intRG;
cpf = intCpf;
fone = intFone;
email = strEmail;
login = strLogin;
senha = strSenha;
tipoUsuario = strTipoUsuario;
logado = strLogado;
}
public String getNome(){
return nome;
}
public void setNome (String strNome){
this.nome = strNome;
}
public int getRG(){
return RG;
}
public void setRG (int intRG){
this.RG = intRG;
}
public int getCpf(){
return cpf;
}
public void setCpf (int strCpf){
this.cpf = strCpf;
}
public int getFone(){
return fone;
}
public void setFone (int intFone){
this.fone = intFone;
}
public String getEmail(){
return email;
}
public void setEmail (String strEmail){
this.email = strEmail;
}
public String getLogin(){
return login;
}
public void setLogin (String strLogin){
this.login = strLogin;
}
public String getSenha(){
return senha;
}
public void setSenha (String strSenha){
this.senha = strSenha;
}
public String getTipoUsuario(){
return tipoUsuario;
}
public void setTipoUsuario (String strTipoUsuario){
this.tipoUsuario = strTipoUsuario;
}
public void setLogado (Boolean strLogado){
this.logado = strLogado;
}
public boolean getLogado(){
return logado;
}
}
UsuarioBD.java
package persistencia;
import java.io.IOException;
import modelo.UsuarioBean;
import java.sql.*;
import java.util.Vector;
/**
-
@author arsoares
*/
public class UsuarioBD {String Nome;
int RG;
int Cpf;
int fone;
String email;
String Login;
String Senha;
String tipoUsuario;
Boolean logado = false;public UsuarioBD()
{}
public static String TipoUsuario(String str) throws IOException
{
String strSQL = “”;
String rt = “”;
Statement stm;
try
{
Connection conn = Conexao.getConnection(); //obtendo conexão
stm = conn.createStatement();
strSQL=“SELECT nome, RG, CPF, telefone, email FROM usuario” + "WHERE CPF=’ " + str + " ’ ";
System.out.println(strSQL);
ResultSet rs = stm.executeQuery(strSQL); //resultado de uma consulta (executeQuery) enviado para um objeto resultSet
if (rs.next())
{
rt = rs.getString(“CPF”);
}
rs.close();
stm.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return rt;
}
// verifica se existe este usuário no BD. O Param bSenha indica se a consulta levará tb em consideração a senha (autenticação)
public static UsuarioBean buscalogin(UsuarioBean u, boolean bSenha) throws IOException
{
String strSQL = “”;
Statement stm;
UsuarioBean uBean = null;
String strNome = u.getNome();
int intRG = u.getRG();
int intCpf = u.getCpf();
int intfone = u.getFone();
String strEmail = u.getEmail();
String strLogin = u.getLogin();
String strSenha = u.getSenha();
String strTipoUsuario = u.getTipoUsuario();
Boolean strLogado = u.getLogado();try
{
Connection conn = Conexao.getConnection(); //obtendo conexão
stm = conn.createStatement();
strSQL = “SELECT login, senha from usuario WHERE login = '” + strLogin + “’ AND senha = '” + strSenha + "’ ";
System.out.println(strSQL);
ResultSet rs = stm.executeQuery(strSQL); //resultado de uma consulta (executeQuery) enviado para um objeto resultSet
if (rs.next())
{
uBean = new UsuarioBean (strNome, rs.getInt(“RG”), rs.getInt(“cpf”), rs.getInt(“fone”), strEmail, strLogin, strSenha, strTipoUsuario, strLogado);
}
rs.close();
stm.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return uBean;
}
// retorna todos os usuários na tabela por meio de objetos UsuarioBean
public static Vector getAll() throws IOException
{
String strSQL = “”;
UsuarioBean u = null;
Statement stm;
Vector vec = new Vector();
String strNome = u.getNome();
int intRG = u.getRG();
int intCpf = u.getCpf();
int intfone = u.getFone();
String strEmail = u.getEmail();
String strLogin = u.getLogin();
String strSenha = u.getSenha();
String strTipoUsuario = u.getTipoUsuario();
Boolean strLogado = u.getLogado();try
{
Connection conn = Conexao.getConnection(); //obtendo conexão
stm = conn.createStatement();
strSQL = “SELECT nome, RG, CPF, telefone, email, tipoUsuario, Login, Senha from usuario WHERE Login = ’ + StrLogin + '” ;
System.out.println(strSQL);
ResultSet rs = stm.executeQuery(strSQL); //resultado de uma consulta (executeQuery) enviado para um objeto resultSet.
while (rs.next())
{
u = new UsuarioBean (strNome, rs.getInt(“RG”), rs.getInt(“cpf”), rs.getInt(“telefone”), strEmail, strLogin, strSenha, strTipoUsuario, strLogado);
vec.addElement(u);
}
rs.close();
stm.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return vec;
}
//retorna um Usuario a partir de seu codigo
public static UsuarioBean getUsuario () throws IOException
{
String strSQL = “”;
UsuarioBean u = null;
Statement stm;
String strNome = u.getNome();
int intRG = u.getRG();
int intCpf = u.getCpf();
int intfone = u.getFone();
String strEmail = u.getEmail();
String strLogin = u.getLogin();
String strSenha = u.getSenha();
String strTipoUsuario = u.getTipoUsuario();
Boolean strLogado = u.getLogado();
try
{
Connection conn = Conexao.getConnection(); //obtendo conexão
stm = conn.createStatement();
strSQL = "SELECT INTO usuario(nome, RG, cpf, telefone, email, login, senha) VALUES ('" + strNome + "', " + intRG + ", " + intCpf + ", " + intfone + ", '" + strEmail + "', '" + strLogin + "', '" + strSenha + "')";
ResultSet rs = stm.executeQuery(strSQL); //resultado de uma consulta (executeQuery) enviado para um objeto resultSet
if (rs.next())
{
u = new UsuarioBean (strNome, rs.getInt("RG"), rs.getInt("cpf"), rs.getInt("telefone"), strEmail, strLogin, strSenha, strTipoUsuario, strLogado);
}
rs.close();
stm.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return u;
}
//Insere Usuário
public static boolean insereUsuario (UsuarioBean u) throws IOException
{
boolean bErro = false;
String strNome = u.getNome();
int intRG = u.getRG();
int intCpf = u.getCpf();
int intfone = u.getFone();
String strEmail = u.getEmail();
String strLogin = u.getLogin();
String strSenha = u.getSenha();
String strTipoUsuario = u.getTipoUsuario();
String sql = null;
boolean strLogado = u.getLogado();
try
{
Connection conn = Conexao.getConnection(); //obtendo conexão
Statement s = conn.createStatement();
UsuarioBean uBD = buscalogin (u, false);
if (uBD != null) // se existir um registro
{
System.out.println("Usuario já existe");
bErro = true;
}
else
sql = "INSERT INTO usuario(nome, RG, cpf, fone, email, login, senha, tipoUsuario) VALUES ('" + strNome + "', " + intRG + ", " + intCpf + ", " + intfone + ", '" + strEmail + "', '" + strLogin + "', '" + strSenha + "', '" + strTipoUsuario + "')";
int i = s.executeUpdate(sql);//ação de inserção no BD (executeUpdate), retorna a quantidade de registros inseridos
if (i != 1)
{
bErro = false;
System.out.println("erro INSERT");
}
s.close();
}
catch (SQLException e){
bErro = true;
System.out.println(“exceção SQL”);
e.printStackTrace();
}
catch (Exception e)
{
bErro = true;
System.out.println(“exceção”);
}
return bErro;
}
public static boolean alteraUsuario (UsuarioBean u) throws IOException
{
boolean bErro = false;
String strNome = u.getNome();
int intRG = u.getRG();
int intCpf = u.getCpf();
int intfone = u.getFone();
String strEmail = u.getEmail();
String strLogin = u.getLogin();
String strSenha = u.getSenha();
String strTipoUsuario = u.getTipoUsuario();
String sql = null;
Boolean strLogado = u.getLogado();
try
{
UsuarioBean uBD = buscalogin (u,false);
int nCpfBD = 0;
if (uBD != null)
nCpfBD = uBD.getCpf();
if (nCpfBD != 0 && (nCpfBD != intCpf)) // já existe
{
System.out.println("Usuario já existe, tente outro login");
bErro = true;
}
else
{
Connection conn = Conexao.getConnection(); //obtendo conexão
String str = "usuario";
sql = "UPDATE INTO usuario(nome, RG, cpf, fone, email, login, senha, tipoUsuario) VALUES ('" + strNome + "', " + intRG + ", " + intCpf + ", " + intfone + ", '" + strEmail + "', '" + strLogin + "', '" + strSenha + "', '" + strTipoUsuario + "')";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, strNome);
ps.setInt(2, intRG);
ps.setInt(3, intCpf);
ps.setInt(4, intfone);
ps.setString(5, strEmail);
ps.setString(6, strLogin);
ps.setString(7, strSenha);
System.out.println(sql);
int i = ps.executeUpdate();
if (i != 1){
bErro = true;
System.out.println ("Erro UPDATE");
}
ps.close();
}
}
catch (SQLException e){
bErro = true;
System.out.println ("exceção SQL");
e.printStackTrace();
}
catch (Exception e){
bErro = true;
System.out.println("exceção");
}
return bErro;
}
public static boolean excluiUsuario (UsuarioBean u) throws IOException
{
boolean bErro = false;
String strNome = u.getNome();
int intRG = u.getRG();
int intCpf = u.getCpf();
int intfone = u.getFone();
String strEmail = u.getEmail();
String strLogin = u.getLogin();
String strSenha = u.getSenha();
String strTipoUsuario = u.getTipoUsuario();
String sql = null;
Boolean strLogado = u.getLogado();
try
{
UsuarioBean uBD = buscalogin (u,false);
if (uBD != null)
{
Connection conn = Conexao.getConnection(); //obtendo conexão
String str = "usuario";
sql = "DELETE INTO usuario(nome, RG, cpf, telefone, email, login, senha) VALUES ('" + strNome + "', " + intRG + ", " + intCpf + ", " + intfone + ", '" + strEmail + "', '" + strLogin + "', '" + strSenha + "')";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, strLogin);
ps.setString(2, strSenha);
ps.setString(3, strNome);
ps.setInt(4, intCpf);
ps.close();
}
}
catch (SQLException e){
bErro = true;
System.out.println ("exceção SQL");
e.printStackTrace();
}
catch (Exception e){
bErro = true;
System.out.println("exceção");
}
return bErro;
}
public static boolean verificarLogin(UsuarioBean u) throws IOException
{
String strSQL = “”;
Statement stm;
UsuarioBean uBean;
String strLogin = u.getLogin();
String strSenha = u.getSenha();
boolean strLogado = u.getLogado();
uBean = new UsuarioBean();
try
{
Connection conn = Conexao.getConnection(); //obtendo conexão
stm = conn.createStatement();
strSQL = "SELECT login, senha from usuario WHERE login = '" + strLogin + "' AND senha = '"+ strSenha + "' " ;
System.out.println(strSQL);
ResultSet rs = stm.executeQuery(strSQL); //resultado de uma consulta (executeQuery) enviado para um objeto resultSet
if (rs.next())
{
u.setLogado(true);
}
rs.close();
stm.close();
}
catch (Exception e)
{
System.out.println("ERRO DE CONEXAO: " + e.getMessage());
}
return u.getLogado();
}
}