Desculpem me se o código estiver um tanto quanto tosco. Lembro que estou apenas aprendendo.
index.jsp
<%--
Document : index
Created on : 16/03/2010, 15:39:11
Author : Alexandro Félix Pereira
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--Cria instâncias das classes userBean e UserDataBean--%>
<jsp:useBean id="user" class="com.vignette.vps.UserBean" scope="page"/>
<jsp:useBean id="userData" class="com.vignette.vps.UserDataBean" scope="page"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pet Plus</title>
</head>
<body>
<%-- Seta todas as propriedades do java bean UserBean, que
equivalem ao nome dos campos "input" abaixo --%>
<jsp:setProperty name="user" property="*"/>
<%
/*Testa se os campos userName ou senha são diferente de null, caso algum seja,
significa que temos uma consulta à ser realizada, caso contrário exibe os
campos para consulta*/
if(user.getUserName() == null |
user.getSenha() == null){
%>
<form action="index.jsp" method="post">
<table>
<tr><th>Usuário:</th>
<th><input name="userName" type="text"/></th>
</tr>
<tr><th>Senha:</th>
<th><input name="senha" type="password"/></th>
</tr>
</table>
<input type="submit" name="Entrar" value="Enviar"/>
</form>
<%
/*Verifica as credenciais do usuário, caso o retorno seja "true", redireciona
o usuário para home.jsp*/
}else if(userData.getCredentials(user.getUserName(), user.getSenha())){
%>
<jsp:forward page = "home.jsp"/>
<%
/*Caso usuário ou senha estejam incorretos, será exibida a mensagem abaixo */
}else{
out.println("Usuário ou senha incorretos");
%>
<br />
<%-- Link recarrega a pagina apos insercao de dados incorreta --%>
<a href="index.jsp">Voltar</a>
<% } %><%-- finaliza o "else" --%>
</body>
</html>
##################################################
home.jsp
<%--
Document : home
Created on : 16/03/2010, 16:17:01
Author : Alexandro Félix Pereira
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Pet Plus</title>
</head>
<body>
<h2><strong>O que deseja fazer?</strong></h2>
<table>
<tr>
<th><a href="listaClientes.jsp">Consultar Clientes</a></th>
</tr>
<tr>
<th><a href="incluirClientes.jsp">Cadastrar Clientes</a></th>
</tr>
</table>
</body>
</html>
##################################################
listaClientes.jsp
<%--
Document : listaClientes
Created on : 17/03/2010, 12:31:29
Author : Alexandro Félix Pereira
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--Cria instâncias das classes userBean e UserDataBean--%>
<jsp:useBean id="userData" class="com.vignette.vps.UserDataBean" scope="page"/>
<jsp:useBean id="user" class="com.vignette.vps.UserBean" scope="page"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Consulta Clientes</title>
</head>
<%--Seta prpriedades--%>
<jsp:setProperty name="user" property="*"/>
<%-- Se nome ou id igual null, exibe a página para consulta --%>
<%
if((user.getId() == null && user.getNome() == null)){
%>
<body>
<h2><strong>O que deseja fazer?</strong></h2>
<form action="listaClientes.jsp">
<table>
<tr>
<th align="left">Id:</th>
<th align="left"><input type="text" name="id" value="" size="30" /></th>
</tr>
<tr>
<th align="left">Nome do cliente:</th>
<th align="left"><input type="text" name="nome" value="" size="30" /></th>
</tr>
</table>
<input type="submit" value="Consultar" name="consultar" />
</form>
<% /*
se o retorno do metodo listaClientes for verdadeiro, exibe o resultado
da consulta
*/
}else if(userData.listaClientes(user.getNome(), user.getId())){
%>
<table width="90%" border="1">
<tr>
<% // write out the header cells containing the column labels
for (int i=1; i<=userData.getColumns(); i++) {
out.write("<th>" + userData.getRsmd().getColumnLabel(i) + "</th>");
}
%>
</tr>
<% // now write out one row for each entry in the database table
while (userData.getResult().next()) {
out.write("<tr>");
for (int i=1; i<=userData.getColumns(); i++) {
out.write("<td>" + userData.getResult().getString(i) + "</td>");
}
out.write("</tr>");
}
}
%>
</table>
</body>
</html>
##################################################
incluirClientes.jsp
<%--
Document : incluirClientes
Created on : Mar 21, 2010, 6:05:29 PM
Author : rideick
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--Cria instâncias das classes userBean e UserDataBean--%>
<jsp:useBean id="user" class="com.vignette.vps.UserBean" scope="request"/>
<jsp:useBean id="userData" class="com.vignette.vps.UserDataBean" scope="request"/>
<HTML>
<HEAD><META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>Incluir Clientes</TITLE>
</HEAD>
<BODY>
<%-- Define as propriedades do bean user--%>
<jsp:setProperty name="user" property="*"/>
<%
//se nome diferente de null exibe a página para inclusão de cliente
if(user.getNome() == null){
%>
<H3>Incluir Cliente</H3>
<FORM action="incluirClientes.jsp" method="get">
<TABLE>
<TBODY><TR><TH align="left">Nome do Cliente:</TH>
<TH><INPUT type="text" name="nome" value="" size="60"></TH>
</TR>
<TR><TH align="left">Endereço:</TH>
<TH><INPUT type="text" name="end1" value="" size="60"></TH>
</TR>
<TR><TH align="left">Endereço Secundário:</TH>
<TH><INPUT type="text" name="end2" size="60"></TH>
</TR>
<TR><TH align="left">CEP:</TH>
<TH><INPUT type="text" name="cep" size="60"></TH>
</TR>
<TR><TH align="left">Cidade:</TH>
<TH><INPUT type="text" name="cidade" size="60"></TH>
</TR>
<TR><TH align="left">Estado</TH>
<TH><INPUT type="text" name="estado" size="60"></TH>
</TR>
<TR><TH align="left">Telefone:</TH>
<TH><INPUT type="text" name="telefone" size="60"></TH>
</TR>
<TR><TH align="left">Fax:</TH>
<TH><INPUT type="text" name="fax" size="60"></TH>
</TR>
<TR><TH align="left">E-mail:</TH>
<TH><INPUT type="text" name="email" size="60"></TH>
</TR>
<TR><TH align="left">Código de Desconto:</TH>
<TH><INPUT type="text" name="cod_desc" size="60"></TH>
</TR>
<TR><TH align="left">Limite de Crédito:</TH>
<TH><INPUT type="text" name="lim_cred" size="60"></TH>
</TR>
</TBODY></TABLE>
<INPUT type="submit" value="Incluir" name="incluir">
</FORM>
<%
}else{
//construcao do sql para inclusão do cliente
userData.setSql(user.getId(),user.getNome(),user.getEnd1(),user.getEnd2(),
user.getCep(),user.getCidade(),user.getEstado(),user.getTelefone(),
user.getFax(),user.getEmail(),user.getCod_desc(),user.getLim_cred());
//se as linhas afetadas maior ou igual a 1, exibe mensagem de sucesso.
}if(userData.getLinhas() >= 1){
%>
<strong>Dados inseridos com sucesso</strong><br />
<a href="incluirClientes.jsp">Voltar</a>
<%
}
%>
</BODY>
</HTML>
##################################################
UserBean.java
package com.vignette.vps;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* @author rideick
*/
public class UserBean implements Serializable{
private String userName,senha,id,nome,end1,end2,
cep,cidade,estado,telefone,fax,email,
cod_desc,lim_cred;
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the senha
*/
public String getSenha() {
return senha;
}
/**
* @param senha the senha to set
*/
public void setSenha(String senha) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(senha.getBytes());
BigInteger hash = new BigInteger(1, md5.digest());
senha = hash.toString(16);
} catch (NoSuchAlgorithmException nsae) {
}
this.senha = senha;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the end1
*/
public String getEnd1() {
return end1;
}
/**
* @param end1 the end1 to set
*/
public void setEnd1(String end1) {
this.end1 = end1;
}
/**
* @return the end2
*/
public String getEnd2() {
return end2;
}
/**
* @param end2 the end2 to set
*/
public void setEnd2(String end2) {
this.end2 = end2;
}
/**
* @return the cep
*/
public String getCep() {
return cep;
}
/**
* @param cep the cep to set
*/
public void setCep(String cep) {
this.cep = cep;
}
/**
* @return the cidade
*/
public String getCidade() {
return cidade;
}
/**
* @param cidade the cidade to set
*/
public void setCidade(String cidade) {
this.cidade = cidade;
}
/**
* @return the estado
*/
public String getEstado() {
return estado;
}
/**
* @param estado the estado to set
*/
public void setEstado(String estado) {
this.estado = estado;
}
/**
* @return the telefone
*/
public String getTelefone() {
return telefone;
}
/**
* @param telefone the telefone to set
*/
public void setTelefone(String telefone) {
this.telefone = telefone;
}
/**
* @return the fax
*/
public String getFax() {
return fax;
}
/**
* @param fax the fax to set
*/
public void setFax(String fax) {
this.fax = fax;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the cod_desc
*/
public String getCod_desc() {
return cod_desc;
}
/**
* @param cod_desc the cod_desc to set
*/
public void setCod_desc(String cod_desc) {
this.cod_desc = cod_desc;
}
/**
* @return the lim_cred
*/
public String getLim_cred() {
return lim_cred;
}
/**
* @param lim_cred the lim_cred to set
*/
public void setLim_cred(String lim_cred) {
this.lim_cred = lim_cred;
}
}
##################################################
UserDataBean.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.vignette.vps;
import javax.naming.NamingException;
import javax.sql.*;
import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
*
* @author Alexandro Felix Pereira
*/
public class UserDataBean {
private Statement pstmt = null;
private PreparedStatement pst = null;
private ResultSetMetaData rsmd = null;
private ResultSet result = null;
private Context ctx = new InitialContext();
private DataSource ds = (DataSource) ctx.lookup("petplus");
private Connection connection = ds.getConnection();
String usrName, pass;
private boolean credentials = false;
private int columns = 0;
private int linhas = 0;
private String sql = null;
UserBean usrBean = new UserBean();
public UserDataBean()
throws SQLException, NamingException{
}
public boolean getCredentials(String userName, String senha)
throws SQLException, NamingException{
String sql = "SELECT user_name,password " +
"FROM users " +
"WHERE user_name='" + userName + "' " +
"AND password='" + senha + "'";
try{
setPstmt(getConnection().createStatement());
setResult(getPstmt().executeQuery(sql));
while(result.next()){
if( getResult().getString("user_name").equals(userName) &&
getResult().getString("password").equals(senha)){
credentials = true;
}
}
}
catch(SQLException e){
System.out.println("Exception na consulta: SELECT user_name,password " +
"FROM users " +
"WHERE user_name='" + userName + "' " +
"AND password='" + senha + "'" + e);
}
return credentials;
}
public boolean listaClientes(String nome, String id) throws SQLException{
setPstmt(getConnection().createStatement());
try{
if (ds != null) {
if(id == null && nome == null){
setResult(getPstmt().executeQuery("SELECT customer_id as id, " +
"name as nome, " + "city as cidade, " +
"" + "phone as telefone, " + "state as estado, " +
"addressline1 as endereço, " +
"addressline2 as endereço_alternativo, " +
"credit_limit as limite_de_crédito " +
"FROM customer " +
"ORDER BY name"));
}else if(id != null && nome == null){
setResult(getPstmt().executeQuery("SELECT customer_id as id, name as nome, city as cidade, " +
"phone as telefone, state as estado, " +
"addressline1 as endereço, " +
"addressline2 as endereço_alternativo, " +
"credit_limit as limite_de_credito " +
"FROM customer " +
"WHERE customer_id=" + id + " " +
"ORDER BY name"));
}else if(id != null && nome != null){
setResult(getPstmt().executeQuery("SELECT customer_id as id, name as nome, city as cidade, " +
"phone as telefone, state as estado, " +
"addressline1 as endereço, " +
"addressline2 as endereço_alternativo, " +
"credit_limit as limite_de_credito " +
"FROM customer " +
"WHERE customer_id=" + id + " " +
"AND LOWER(name) LIKE '%" + nome + "%' " +
"ORDER BY name"));
}else{
setResult(getPstmt().executeQuery("SELECT customer_id as id, name as nome, city as cidade, " +
"phone as telefone, state as estado, " +
"addressline1 as endereço, " +
"addressline2 as endereço_alternativo, " +
"credit_limit as limite_de_credito " +
"FROM customer " +
"WHERE LOWER(name) " +
"LIKE '%" + nome + "%' " +
"ORDER BY name"));
}
if(result != null ){
credentials = true;
}
}
}
catch (SQLException e) {
System.out.println("Error occurred " + e);
}
try {
setRsmd(getResult().getMetaData());
setColumns(getRsmd().getColumnCount());
}
catch (SQLException e) {
System.out.println("Error occurred " + e);
}
return credentials;
}
public void setSql(String id,String nome,String end1,String end2,
String cep,String cidade,String estado,String telefone,
String fax,String email,String cod_desc,String lim_cred) throws SQLException{
pstmt = connection.createStatement();
sql = "INSERT INTO customer " +
"(discount_code, zip, name, " +
"addressline1, addressline2, city, state, phone, " +
"fax, email, credit_limit) " +
"VALUES ('" + cod_desc + "','" +
cep +"','" + nome + "','" + end1 + "','" + end2 +"','" +
cidade + "','" + estado + "','" + telefone
+ "','" + fax + "','" + email + "'," + lim_cred + ")";
setLinhas(pstmt.executeUpdate(sql));
}
public String getSql(){
return sql;
}
/**
* @return the columns
*/
public int getColumns() {
return columns;
}
/**
* @param columns the columns to set
*/
public void setColumns(int columns) {
this.columns = columns;
}
/**
* @return the rsmd
*/
public ResultSetMetaData getRsmd() {
return rsmd;
}
/**
* @param rsmd the rsmd to set
*/
public void setRsmd(ResultSetMetaData rsmd) {
this.rsmd = rsmd;
}
/**
* @return the result
*/
public ResultSet getResult() {
return result;
}
/**
* @param result the result to set
*/
public void setResult(ResultSet result) {
this.result = result;
}
/**
* @return the connection
*/
public Connection getConnection() {
return connection;
}
/**
* @param connection the connection to set
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return the pstmt
*/
public Statement getPstmt() {
return pstmt;
}
/**
* @param pstmt the pstmt to set
*/
public void setPstmt(Statement pstmt) {
this.pstmt = pstmt;
}
/**
* @return the pst
*/
public PreparedStatement getPst() {
return pst;
}
/**
* @param pst the pst to set
*/
public void setPst(String sql) throws SQLException {
pst = connection.prepareStatement(sql);
}
/**
* @return the linhas
*/
public int getLinhas() {
return linhas;
}
/**
* @param linhas the linhas to set
*/
public void setLinhas(int linhas) {
this.linhas = linhas;
}
@Override
public void finalize() throws SQLException{
try{
result.close();
connection.close();
pstmt.close();
}
catch(SQLException e){
System.out.print(e);
}
}
}
Nenhum comentário:
Postar um comentário