From fa595180ae707f4804922bbec028ae2bd8475879 Mon Sep 17 00:00:00 2001 From: Iago Colodetti Date: Sat, 6 Apr 2019 18:57:06 -0300 Subject: [PATCH] =?UTF-8?q?Adicionada=20a=20restri=C3=A7=C3=A3o=20"UNIQUE"?= =?UTF-8?q?=20no=20arquivo=20"agendadb.sql"=20em=20"Usuario=20=3D>=20nome"?= =?UTF-8?q?,=20por=20isso=20o=20m=C3=A9todo=20"usuarioExiste(String=20nome?= =?UTF-8?q?)"=20da=20classe=20UsuarioDAO=20foi=20removido=20e=20no=20Catch?= =?UTF-8?q?=20(SQLException)=20do=20m=C3=A9todo=20cadastrar=20adicionada?= =?UTF-8?q?=20uma=20condicional,=20no=20qual=20se=20o=20c=C3=B3digo=20do?= =?UTF-8?q?=20erro=20gerado=20pelo=20mysql=20for=20o=20c=C3=B3digo=20imped?= =?UTF-8?q?indo=20a=20adi=C3=A7=C3=A3o=20de=20nomes=20iguais,=20lan=C3=A7a?= =?UTF-8?q?r=20a=20exce=C3=A7=C3=A3o;=20Adicionadas=20as=20interfaces=20Us?= =?UTF-8?q?uarioDAO=20e=20ContatoDAO,=20as=20classes=20antes=20UsuarioDAO?= =?UTF-8?q?=20e=20ContatoDAO=20foram=20renomoeadas=20para=20UsuarioDAOImpl?= =?UTF-8?q?=20e=20ContatoDAOImpl;=20Contato=20e=20Usuario=20agora=20implem?= =?UTF-8?q?entam=20Serializable.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 +- .../controle/ConnectionFactory.java | 20 +- .../controle/FiltroAutenticacao.java | 20 +- .../iagocolodetti/controle/ServletAgenda.java | 21 +- .../controle/ServletAlterar.java | 29 +-- .../controle/ServletCadastrar.java | 25 +-- .../iagocolodetti/controle/ServletIndex.java | 9 +- .../iagocolodetti/controle/ServletLogin.java | 21 +- .../iagocolodetti/controle/ServletLogout.java | 6 +- .../iagocolodetti/controle/ServletNovo.java | 21 +- .../controle/ServletRemover.java | 19 +- .../br/com/iagocolodetti/controle/Util.java | 10 +- .../br/com/iagocolodetti/modelo/Contato.java | 22 +- .../com/iagocolodetti/modelo/ContatoDAO.java | 165 ++------------- .../iagocolodetti/modelo/ContatoDAOImpl.java | 190 ++++++++++++++++++ .../modelo/ContatoExisteException.java | 7 +- .../modelo/ContatoNaoExisteException.java | 7 +- .../br/com/iagocolodetti/modelo/Usuario.java | 16 +- .../com/iagocolodetti/modelo/UsuarioDAO.java | 110 +--------- .../iagocolodetti/modelo/UsuarioDAOImpl.java | 89 ++++++++ .../modelo/UsuarioExisteException.java | 7 +- web/agenda.jsp | 5 +- web/alterar.jsp | 1 + web/cadastrar.jsp | 1 + web/css/estilos.css | 1 + web/index.jsp | 1 + web/js/app.js | 3 + web/novo.jsp | 1 + 28 files changed, 476 insertions(+), 359 deletions(-) create mode 100644 src/java/br/com/iagocolodetti/modelo/ContatoDAOImpl.java create mode 100644 src/java/br/com/iagocolodetti/modelo/UsuarioDAOImpl.java diff --git a/README.md b/README.md index 65657e4..b39884a 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Também é possível efetuar o logout e um filtro é usado para verificar a cada Aplicação criada com o padrão MVC, utilizando classe Java como modelo, página JSP como view (com Bootstrap 3 e JSTL) e Servlet como controller. * Downloads: https://github.com/iagocolodetti/Agenda/releases - * [Arquivo de Implantação](https://github.com/iagocolodetti/Agenda/releases/download/v2.2/Agenda.war "Agenda.war") - * [Arquivo de Script MySQL](https://github.com/iagocolodetti/Agenda/releases/download/v2.2/agendadb.sql "agendadb.sql") - * [Bibliotecas Necessárias](https://github.com/iagocolodetti/Agenda/releases/download/v2.2/bibliotecas.zip "bibliotecas.zip") - * [Código-Fonte](https://github.com/iagocolodetti/Agenda/archive/v2.2.zip "v2.2.zip") + * [Arquivo de Implantação](https://github.com/iagocolodetti/Agenda/releases/download/v2.3/Agenda.war "Agenda.war") + * [Arquivo de Script MySQL](https://github.com/iagocolodetti/Agenda/releases/download/v2.3/agendadb.sql "agendadb.sql") + * [Bibliotecas Necessárias](https://github.com/iagocolodetti/Agenda/releases/download/v2.3/bibliotecas.zip "bibliotecas.zip") + * [Código-Fonte](https://github.com/iagocolodetti/Agenda/archive/v2.3.zip "v2.3.zip") diff --git a/src/java/br/com/iagocolodetti/controle/ConnectionFactory.java b/src/java/br/com/iagocolodetti/controle/ConnectionFactory.java index 9810569..6f5b670 100644 --- a/src/java/br/com/iagocolodetti/controle/ConnectionFactory.java +++ b/src/java/br/com/iagocolodetti/controle/ConnectionFactory.java @@ -6,6 +6,10 @@ import java.sql.ResultSet; import java.sql.SQLException; +/** + * + * @author iagocolodetti + */ public class ConnectionFactory { private static final String DRIVER = "com.mysql.jdbc.Driver"; @@ -14,25 +18,23 @@ public class ConnectionFactory { private static final String PASS = "root"; public static Connection getConnection() { - + try { Class.forName(DRIVER); return DriverManager.getConnection(URL, USER, PASS); - } - catch (ClassNotFoundException | SQLException e) { + } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return null; } public static void closeConnection(Connection con) { - + try { if (con != null) { con.close(); } - } - catch (SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -44,8 +46,7 @@ public static void closeConnection(Connection con, PreparedStatement ps) { if (ps != null) { ps.close(); } - } - catch (SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } } @@ -57,8 +58,7 @@ public static void closeConnection(Connection con, PreparedStatement ps, ResultS if (rs != null) { rs.close(); } - } - catch (SQLException e) { + } catch (SQLException e) { e.printStackTrace(); } } diff --git a/src/java/br/com/iagocolodetti/controle/FiltroAutenticacao.java b/src/java/br/com/iagocolodetti/controle/FiltroAutenticacao.java index 1e4c0f5..bcc1b75 100644 --- a/src/java/br/com/iagocolodetti/controle/FiltroAutenticacao.java +++ b/src/java/br/com/iagocolodetti/controle/FiltroAutenticacao.java @@ -9,19 +9,23 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; +/** + * + * @author iagocolodetti + */ public class FiltroAutenticacao implements Filter { - + @Override public void init(FilterConfig filterConfig) { - + } - + @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - - HttpServletRequest rq = (HttpServletRequest)request; + + HttpServletRequest rq = (HttpServletRequest) request; if (rq.getSession().isNew() || rq.getSession().getAttribute("usuario") == null) { rq.setAttribute("erro", "Sessão expirada, faça o login novamente."); rq.getSession().invalidate(); @@ -30,9 +34,9 @@ public void doFilter(ServletRequest request, ServletResponse response, chain.doFilter(request, response); } - + @Override - public void destroy() { - + public void destroy() { + } } diff --git a/src/java/br/com/iagocolodetti/controle/ServletAgenda.java b/src/java/br/com/iagocolodetti/controle/ServletAgenda.java index 58404ac..29a6d5d 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletAgenda.java +++ b/src/java/br/com/iagocolodetti/controle/ServletAgenda.java @@ -1,7 +1,7 @@ package br.com.iagocolodetti.controle; import br.com.iagocolodetti.modelo.Contato; -import br.com.iagocolodetti.modelo.ContatoDAO; +import br.com.iagocolodetti.modelo.ContatoDAOImpl; import br.com.iagocolodetti.modelo.Usuario; import java.io.IOException; import java.util.ArrayList; @@ -10,20 +10,27 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletAgenda extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + Usuario usuario = (Usuario) request.getSession().getAttribute("usuario"); - + if (!request.getSession().isNew() && usuario != null) { - ArrayList contatos = new ContatoDAO().carregar(usuario); - if (!contatos.isEmpty()) request.setAttribute("contatos", contatos); - else request.setAttribute("agendavazia", "A agenda ainda não possui contatos."); + ArrayList contatos = new ContatoDAOImpl().carregar(usuario); + if (!contatos.isEmpty()) { + request.setAttribute("contatos", contatos); + } else { + request.setAttribute("agendavazia", "A agenda ainda não possui contatos."); + } } - + request.getRequestDispatcher("agenda.jsp").forward(request, response); } } diff --git a/src/java/br/com/iagocolodetti/controle/ServletAlterar.java b/src/java/br/com/iagocolodetti/controle/ServletAlterar.java index c378490..efd8ef5 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletAlterar.java +++ b/src/java/br/com/iagocolodetti/controle/ServletAlterar.java @@ -1,7 +1,7 @@ package br.com.iagocolodetti.controle; import br.com.iagocolodetti.modelo.Contato; -import br.com.iagocolodetti.modelo.ContatoDAO; +import br.com.iagocolodetti.modelo.ContatoDAOImpl; import br.com.iagocolodetti.modelo.ContatoExisteException; import br.com.iagocolodetti.modelo.ContatoNaoExisteException; import br.com.iagocolodetti.modelo.Usuario; @@ -12,6 +12,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletAlterar extends HttpServlet { private void erro(HttpServletRequest request, String erro) { @@ -23,27 +27,27 @@ private void erro(HttpServletRequest request, String erro) { request.setAttribute("novoemail", Util.decodificar(request.getParameter("novoemail"))); request.setAttribute("novotelefone", Util.decodificar(request.getParameter("novotelefone"))); } - + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + request.setAttribute("id", Util.decodificar(request.getParameter("id"))); request.setAttribute("nomeatual", Util.decodificar(request.getParameter("nome"))); request.setAttribute("emailatual", Util.decodificar(request.getParameter("email"))); request.setAttribute("telefoneatual", Util.decodificar(request.getParameter("telefone"))); - + request.getRequestDispatcher("alterar.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + RequestDispatcher rd = null; - + Usuario usuario = (Usuario) request.getSession().getAttribute("usuario"); - + if (!request.getSession().isNew() && usuario != null) { try { Contato contato = new Contato( @@ -51,18 +55,17 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Util.decodificar(request.getParameter("novonome")), Util.decodificar(request.getParameter("novoemail")), Util.decodificar(request.getParameter("novotelefone"))); - - new ContatoDAO().alterar(usuario.getId(), contato); - + + new ContatoDAOImpl().alterar(usuario.getId(), contato); + request.setAttribute("sucesso", "Contato alterado com sucesso."); rd = request.getRequestDispatcher("agenda"); - } - catch (IndexOutOfBoundsException | IllegalArgumentException | ContatoExisteException | ContatoNaoExisteException e) { + } catch (IndexOutOfBoundsException | IllegalArgumentException | ContatoExisteException | ContatoNaoExisteException e) { erro(request, e.getMessage()); rd = request.getRequestDispatcher("alterar.jsp"); } } - + rd.forward(request, response); } } diff --git a/src/java/br/com/iagocolodetti/controle/ServletCadastrar.java b/src/java/br/com/iagocolodetti/controle/ServletCadastrar.java index ec1f744..c7a9986 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletCadastrar.java +++ b/src/java/br/com/iagocolodetti/controle/ServletCadastrar.java @@ -1,7 +1,7 @@ package br.com.iagocolodetti.controle; import br.com.iagocolodetti.modelo.Usuario; -import br.com.iagocolodetti.modelo.UsuarioDAO; +import br.com.iagocolodetti.modelo.UsuarioDAOImpl; import br.com.iagocolodetti.modelo.UsuarioExisteException; import java.io.IOException; import javax.servlet.ServletException; @@ -9,39 +9,40 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletCadastrar extends HttpServlet { private void erro(HttpServletRequest request, String erro) { request.setAttribute("erro", "Erro: " + erro); request.setAttribute("nome", Util.decodificar(request.getParameter("nome"))); } - + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + if (!request.getSession().isNew() && request.getSession().getAttribute("usuario") != null) { response.sendRedirect("agenda"); - } - else { + } else { response.sendRedirect("cadastrar.jsp"); } } - + @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + if (!request.getSession().isNew() && request.getSession().getAttribute("usuario") != null) { response.sendRedirect("agenda"); - } - else { + } else { try { Usuario usuario = new Usuario(Util.decodificar(request.getParameter("nome")), Util.decodificar(request.getParameter("senha"))); - new UsuarioDAO().cadastrar(usuario); + new UsuarioDAOImpl().cadastrar(usuario); request.setAttribute("sucesso", "Usuário \"" + usuario.getNome() + "\" cadastrado com sucesso."); - } - catch (IllegalArgumentException | IndexOutOfBoundsException | UsuarioExisteException e) { + } catch (IllegalArgumentException | IndexOutOfBoundsException | UsuarioExisteException e) { erro(request, e.getMessage()); } request.getRequestDispatcher("cadastrar.jsp").forward(request, response); diff --git a/src/java/br/com/iagocolodetti/controle/ServletIndex.java b/src/java/br/com/iagocolodetti/controle/ServletIndex.java index 6475d47..35fe3d5 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletIndex.java +++ b/src/java/br/com/iagocolodetti/controle/ServletIndex.java @@ -6,16 +6,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletIndex extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + if (!request.getSession().isNew() && request.getSession().getAttribute("usuario") != null) { response.sendRedirect("agenda"); - } - else { + } else { response.sendRedirect("index.jsp"); } } diff --git a/src/java/br/com/iagocolodetti/controle/ServletLogin.java b/src/java/br/com/iagocolodetti/controle/ServletLogin.java index 668c1f1..2dd5f44 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletLogin.java +++ b/src/java/br/com/iagocolodetti/controle/ServletLogin.java @@ -1,7 +1,7 @@ package br.com.iagocolodetti.controle; import br.com.iagocolodetti.modelo.Usuario; -import br.com.iagocolodetti.modelo.UsuarioDAO; +import br.com.iagocolodetti.modelo.UsuarioDAOImpl; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; @@ -10,31 +10,34 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +/** + * + * @author iagocolodetti + */ public class ServletLogin extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + RequestDispatcher rd; - - Usuario usuario = new UsuarioDAO().buscar(new Usuario(request.getParameter("nome"), request.getParameter("senha"))); - + + Usuario usuario = new UsuarioDAOImpl().buscar(new Usuario(request.getParameter("nome"), request.getParameter("senha"))); + if (usuario.getId() != -1) { HttpSession objSessao = request.getSession(); if (objSessao == null) { objSessao = request.getSession(true); } objSessao.setAttribute("usuario", usuario); - + rd = request.getRequestDispatcher("agenda"); - } - else { + } else { request.setAttribute("nome", Util.decodificar(usuario.getNome())); request.setAttribute("erro", "Erro: Usuário e/ou senha inválido(s)"); rd = request.getRequestDispatcher("index.jsp"); } - + rd.forward(request, response); } } diff --git a/src/java/br/com/iagocolodetti/controle/ServletLogout.java b/src/java/br/com/iagocolodetti/controle/ServletLogout.java index 020f98e..b687dfc 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletLogout.java +++ b/src/java/br/com/iagocolodetti/controle/ServletLogout.java @@ -6,12 +6,16 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletLogout extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + request.getSession().invalidate(); response.sendRedirect("index.jsp"); } diff --git a/src/java/br/com/iagocolodetti/controle/ServletNovo.java b/src/java/br/com/iagocolodetti/controle/ServletNovo.java index f9fb156..006f8fd 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletNovo.java +++ b/src/java/br/com/iagocolodetti/controle/ServletNovo.java @@ -2,7 +2,7 @@ import br.com.iagocolodetti.modelo.ContatoExisteException; import br.com.iagocolodetti.modelo.Contato; -import br.com.iagocolodetti.modelo.ContatoDAO; +import br.com.iagocolodetti.modelo.ContatoDAOImpl; import br.com.iagocolodetti.modelo.Usuario; import java.io.IOException; import javax.servlet.ServletException; @@ -10,6 +10,10 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletNovo extends HttpServlet { private void erro(HttpServletRequest request, String erro) { @@ -18,31 +22,30 @@ private void erro(HttpServletRequest request, String erro) { request.setAttribute("email", Util.decodificar(request.getParameter("email"))); request.setAttribute("telefone", Util.decodificar(request.getParameter("telefone"))); } - + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + response.sendRedirect("novo.jsp"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + Usuario usuario = (Usuario) request.getSession().getAttribute("usuario"); - + if (!request.getSession().isNew() && usuario != null) { try { Contato contato = new Contato(Util.decodificar(request.getParameter("nome")), Util.decodificar(request.getParameter("email")), Util.decodificar(request.getParameter("telefone"))); - new ContatoDAO().cadastrar(usuario.getId(), contato); + new ContatoDAOImpl().cadastrar(usuario.getId(), contato); request.setAttribute("sucesso", "Novo contato cadastrado com sucesso."); - } - catch (IndexOutOfBoundsException | IllegalArgumentException | ContatoExisteException e) { + } catch (IndexOutOfBoundsException | IllegalArgumentException | ContatoExisteException e) { erro(request, e.getMessage()); } } - + request.getRequestDispatcher("novo.jsp").forward(request, response); } } diff --git a/src/java/br/com/iagocolodetti/controle/ServletRemover.java b/src/java/br/com/iagocolodetti/controle/ServletRemover.java index cb0d8a4..5ce1527 100644 --- a/src/java/br/com/iagocolodetti/controle/ServletRemover.java +++ b/src/java/br/com/iagocolodetti/controle/ServletRemover.java @@ -2,7 +2,7 @@ import br.com.iagocolodetti.modelo.ContatoNaoExisteException; import br.com.iagocolodetti.modelo.Contato; -import br.com.iagocolodetti.modelo.ContatoDAO; +import br.com.iagocolodetti.modelo.ContatoDAOImpl; import br.com.iagocolodetti.modelo.Usuario; import java.io.IOException; import javax.servlet.ServletException; @@ -10,14 +10,18 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +/** + * + * @author iagocolodetti + */ public class ServletRemover extends HttpServlet { - + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - + Usuario usuario = (Usuario) request.getSession().getAttribute("usuario"); - + if (!request.getSession().isNew() && usuario != null) { try { Contato contato = new Contato( @@ -25,14 +29,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) Util.decodificar(request.getParameter("nome")), Util.decodificar(request.getParameter("email")), Util.decodificar(request.getParameter("telefone"))); - new ContatoDAO().remover(usuario.getId(), contato); + new ContatoDAOImpl().remover(usuario.getId(), contato); request.setAttribute("sucesso", "Contato removido com sucesso."); - } - catch (ContatoNaoExisteException e) { + } catch (ContatoNaoExisteException e) { request.setAttribute("erro", "Erro: " + e.getMessage()); } } - + request.getRequestDispatcher("agenda").forward(request, response); } } diff --git a/src/java/br/com/iagocolodetti/controle/Util.java b/src/java/br/com/iagocolodetti/controle/Util.java index 72aa706..213f952 100644 --- a/src/java/br/com/iagocolodetti/controle/Util.java +++ b/src/java/br/com/iagocolodetti/controle/Util.java @@ -3,16 +3,20 @@ import java.nio.charset.StandardCharsets; import org.mindrot.jbcrypt.BCrypt; +/** + * + * @author iagocolodetti + */ public class Util { - + public static String decodificar(String codificado) { return (new String(codificado.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8)); } - + public static String criptografar(String senha) { return BCrypt.hashpw(senha, BCrypt.gensalt()); } - + public static boolean verificarSenha(String senha, String criptografada) { return BCrypt.checkpw(senha, criptografada); } diff --git a/src/java/br/com/iagocolodetti/modelo/Contato.java b/src/java/br/com/iagocolodetti/modelo/Contato.java index f4ba324..3fe5d71 100644 --- a/src/java/br/com/iagocolodetti/modelo/Contato.java +++ b/src/java/br/com/iagocolodetti/modelo/Contato.java @@ -1,35 +1,41 @@ package br.com.iagocolodetti.modelo; +/** + * + * @author iagocolodetti + */ public class Contato implements java.io.Serializable { + + private static final long serialVersionUID = -2319598745423332344L; private int id; private String nome, email, telefone; public Contato() { - + } - + public Contato(String nome, String email, String telefone) { this.nome = nome; this.email = email; this.telefone = telefone; } - + public Contato(int id, String nome, String email, String telefone) { this.id = id; this.nome = nome; this.email = email; this.telefone = telefone; } - + public int getId() { return id; } - + public void setId(int id) { this.id = id; } - + public String getNome() { return nome; } @@ -53,9 +59,9 @@ public String getTelefone() { public void setTelefone(String telefone) { this.telefone = telefone; } - + public boolean equals(Contato contato) { - return contato instanceof Contato + return contato instanceof Contato && getNome().equals((contato).getNome()) && getEmail().equals((contato).getEmail()) && getTelefone().equals((contato).getTelefone()); diff --git a/src/java/br/com/iagocolodetti/modelo/ContatoDAO.java b/src/java/br/com/iagocolodetti/modelo/ContatoDAO.java index 60f055e..55ecfbe 100644 --- a/src/java/br/com/iagocolodetti/modelo/ContatoDAO.java +++ b/src/java/br/com/iagocolodetti/modelo/ContatoDAO.java @@ -1,160 +1,21 @@ package br.com.iagocolodetti.modelo; -import br.com.iagocolodetti.controle.ConnectionFactory; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; +/** + * + * @author iagocolodetti + */ +public interface ContatoDAO { -public class ContatoDAO { - - // Create - public void cadastrar(int usuario_id, Contato contato) throws IndexOutOfBoundsException, IllegalArgumentException, ContatoExisteException { - - if (contato.getNome().length() > 50) throw new IndexOutOfBoundsException("Nome do contato contém mais que 50 caracteres."); - - if (contato.getEmail().contains(" ")) throw new IllegalArgumentException("Email do contato contém espaços."); - if (contato.getEmail().length() > 70) throw new IndexOutOfBoundsException("Email do contato contém mais que 70 caracteres."); - - if (contato.getTelefone().contains(" ")) throw new IllegalArgumentException("Telefone do contato contém espaços."); - if (contato.getTelefone().length() > 13) throw new IndexOutOfBoundsException("Telefone do contato contém mais que 13 caracteres."); - - if (contatoExiste(usuario_id, contato)) throw new ContatoExisteException(); - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; + public void cadastrar(int usuario_id, Contato contato) + throws IndexOutOfBoundsException, IllegalArgumentException, ContatoExisteException; - try { - ps = con.prepareStatement("INSERT INTO contato(nome, email, telefone, usuario_id) VALUES(?, ?, ?, ?)"); - ps.setString(1, contato.getNome()); - ps.setString(2, contato.getEmail()); - ps.setString(3, contato.getTelefone()); - ps.setInt(4, usuario_id); + public java.util.ArrayList carregar(Usuario usuario); - ps.executeUpdate(); - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps); - } - } - - // Read - public ArrayList carregar(Usuario usuario) { - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; - ResultSet rs = null; + public boolean contatoExiste(int usuario_id, Contato contato); - ArrayList contatos = new ArrayList<>(); + public void alterar(int usuario_id, Contato contato) + throws IndexOutOfBoundsException, IllegalArgumentException, ContatoExisteException, ContatoNaoExisteException; - try { - ps = con.prepareStatement("SELECT * FROM contato WHERE usuario_id = ?"); - ps.setInt(1, usuario.getId()); - rs = ps.executeQuery(); - - while (rs.next()) { - Contato contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("email"), rs.getString("telefone")); - contatos.add(contato); - } - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps, rs); - } - - return contatos; - } - - // A ideia aqui é checar se o contato existe pelos seus parâmetros. - public boolean contatoExiste(int usuario_id, Contato contato) { - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; - ResultSet rs = null; - - boolean existe = false; - - try { - ps = con.prepareStatement("SELECT id FROM contato WHERE nome = ? and email = ? and telefone = ? and usuario_id = ?"); - ps.setString(1, contato.getNome()); - ps.setString(2, contato.getEmail()); - ps.setString(3, contato.getTelefone()); - ps.setInt(4, usuario_id); - - rs = ps.executeQuery(); - - if (rs.next()) { - existe = true; - } - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps, rs); - } - - return existe; - } - - // Update - public void alterar(int usuario_id, Contato contato) throws IndexOutOfBoundsException, IllegalArgumentException, ContatoExisteException, ContatoNaoExisteException { - - if (contato.getNome().length() > 50) throw new IndexOutOfBoundsException("Novo nome do contato contém mais que 50 caracteres."); - - if (contato.getEmail().contains(" ")) throw new IllegalArgumentException("Novo email do contato contém espaços."); - if (contato.getEmail().length() > 70) throw new IndexOutOfBoundsException("Novo email do contato contém mais que 70 caracteres."); - - if (contato.getTelefone().contains(" ")) throw new IllegalArgumentException("Novo telefone do contato contém espaços."); - if (contato.getTelefone().length() > 13) throw new IndexOutOfBoundsException("Novo telefone do contato contém mais que 13 caracteres."); - - if (contatoExiste(usuario_id, contato)) throw new ContatoExisteException(); - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; - - try { - ps = con.prepareStatement("UPDATE contato SET nome = ?, email = ?, telefone = ? WHERE id = ? AND usuario_id = ?"); - ps.setString(1, contato.getNome()); - ps.setString(2, contato.getEmail()); - ps.setString(3, contato.getTelefone()); - ps.setInt(4, contato.getId()); - ps.setInt(5, usuario_id); - - if (ps.executeUpdate() == 0) throw new ContatoNaoExisteException(); - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps); - } - } - - // Delete - public void remover(int usuario_id, Contato contato) throws ContatoNaoExisteException { - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; - - try { - ps = con.prepareStatement("DELETE FROM contato WHERE id = ? AND usuario_id = ?"); - ps.setInt(1, contato.getId()); - ps.setInt(2, usuario_id); - - if (ps.executeUpdate() == 0) throw new ContatoNaoExisteException(); - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps); - } - } + public void remover(int usuario_id, Contato contato) + throws ContatoNaoExisteException; } diff --git a/src/java/br/com/iagocolodetti/modelo/ContatoDAOImpl.java b/src/java/br/com/iagocolodetti/modelo/ContatoDAOImpl.java new file mode 100644 index 0000000..c7ba486 --- /dev/null +++ b/src/java/br/com/iagocolodetti/modelo/ContatoDAOImpl.java @@ -0,0 +1,190 @@ +package br.com.iagocolodetti.modelo; + +import br.com.iagocolodetti.controle.ConnectionFactory; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; + +/** + * + * @author iagocolodetti + */ +public class ContatoDAOImpl implements ContatoDAO { + + // Create + @Override + public void cadastrar(int usuario_id, Contato contato) + throws IndexOutOfBoundsException, IllegalArgumentException, ContatoExisteException { + + if (contato.getNome().length() > 50) { + throw new IndexOutOfBoundsException("Nome do contato contém mais que 50 caracteres."); + } + + if (contato.getEmail().contains(" ")) { + throw new IllegalArgumentException("Email do contato contém espaços."); + } + if (contato.getEmail().length() > 70) { + throw new IndexOutOfBoundsException("Email do contato contém mais que 70 caracteres."); + } + + if (contato.getTelefone().contains(" ")) { + throw new IllegalArgumentException("Telefone do contato contém espaços."); + } + if (contato.getTelefone().length() > 13) { + throw new IndexOutOfBoundsException("Telefone do contato contém mais que 13 caracteres."); + } + + if (contatoExiste(usuario_id, contato)) { + throw new ContatoExisteException(); + } + + Connection con = ConnectionFactory.getConnection(); + PreparedStatement ps = null; + + try { + ps = con.prepareStatement("INSERT INTO contato(nome, email, telefone, usuario_id) VALUES(?, ?, ?, ?)"); + ps.setString(1, contato.getNome()); + ps.setString(2, contato.getEmail()); + ps.setString(3, contato.getTelefone()); + ps.setInt(4, usuario_id); + + ps.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionFactory.closeConnection(con, ps); + } + } + + // Read + @Override + public ArrayList carregar(Usuario usuario) { + + Connection con = ConnectionFactory.getConnection(); + PreparedStatement ps = null; + ResultSet rs = null; + + ArrayList contatos = new ArrayList<>(); + + try { + ps = con.prepareStatement("SELECT * FROM contato WHERE usuario_id = ?"); + ps.setInt(1, usuario.getId()); + rs = ps.executeQuery(); + + while (rs.next()) { + Contato contato = new Contato(rs.getInt("id"), rs.getString("nome"), rs.getString("email"), rs.getString("telefone")); + contatos.add(contato); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionFactory.closeConnection(con, ps, rs); + } + + return contatos; + } + + // A ideia aqui é checar se o contato existe pelos seus parâmetros. + @Override + public boolean contatoExiste(int usuario_id, Contato contato) { + + Connection con = ConnectionFactory.getConnection(); + PreparedStatement ps = null; + ResultSet rs = null; + + boolean existe = false; + + try { + ps = con.prepareStatement("SELECT id FROM contato WHERE nome = ? and email = ? and telefone = ? and usuario_id = ?"); + ps.setString(1, contato.getNome()); + ps.setString(2, contato.getEmail()); + ps.setString(3, contato.getTelefone()); + ps.setInt(4, usuario_id); + + rs = ps.executeQuery(); + + if (rs.next()) { + existe = true; + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionFactory.closeConnection(con, ps, rs); + } + + return existe; + } + + // Update + @Override + public void alterar(int usuario_id, Contato contato) + throws IndexOutOfBoundsException, IllegalArgumentException, ContatoExisteException, ContatoNaoExisteException { + + if (contato.getNome().length() > 50) { + throw new IndexOutOfBoundsException("Novo nome do contato contém mais que 50 caracteres."); + } + + if (contato.getEmail().contains(" ")) { + throw new IllegalArgumentException("Novo email do contato contém espaços."); + } + if (contato.getEmail().length() > 70) { + throw new IndexOutOfBoundsException("Novo email do contato contém mais que 70 caracteres."); + } + + if (contato.getTelefone().contains(" ")) { + throw new IllegalArgumentException("Novo telefone do contato contém espaços."); + } + if (contato.getTelefone().length() > 13) { + throw new IndexOutOfBoundsException("Novo telefone do contato contém mais que 13 caracteres."); + } + + if (contatoExiste(usuario_id, contato)) { + throw new ContatoExisteException(); + } + + Connection con = ConnectionFactory.getConnection(); + PreparedStatement ps = null; + + try { + ps = con.prepareStatement("UPDATE contato SET nome = ?, email = ?, telefone = ? WHERE id = ? AND usuario_id = ?"); + ps.setString(1, contato.getNome()); + ps.setString(2, contato.getEmail()); + ps.setString(3, contato.getTelefone()); + ps.setInt(4, contato.getId()); + ps.setInt(5, usuario_id); + + if (ps.executeUpdate() == 0) { + throw new ContatoNaoExisteException(); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionFactory.closeConnection(con, ps); + } + } + + // Delete + @Override + public void remover(int usuario_id, Contato contato) + throws ContatoNaoExisteException { + + Connection con = ConnectionFactory.getConnection(); + PreparedStatement ps = null; + + try { + ps = con.prepareStatement("DELETE FROM contato WHERE id = ? AND usuario_id = ?"); + ps.setInt(1, contato.getId()); + ps.setInt(2, usuario_id); + + if (ps.executeUpdate() == 0) { + throw new ContatoNaoExisteException(); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionFactory.closeConnection(con, ps); + } + } +} diff --git a/src/java/br/com/iagocolodetti/modelo/ContatoExisteException.java b/src/java/br/com/iagocolodetti/modelo/ContatoExisteException.java index 4543826..83e32e8 100644 --- a/src/java/br/com/iagocolodetti/modelo/ContatoExisteException.java +++ b/src/java/br/com/iagocolodetti/modelo/ContatoExisteException.java @@ -1,10 +1,15 @@ package br.com.iagocolodetti.modelo; +/** + * + * @author iagocolodetti + */ public class ContatoExisteException extends Exception { + public ContatoExisteException() { super("Contato já existe."); } - + public ContatoExisteException(String mensagem) { super(mensagem); } diff --git a/src/java/br/com/iagocolodetti/modelo/ContatoNaoExisteException.java b/src/java/br/com/iagocolodetti/modelo/ContatoNaoExisteException.java index 48ebed7..390e65f 100644 --- a/src/java/br/com/iagocolodetti/modelo/ContatoNaoExisteException.java +++ b/src/java/br/com/iagocolodetti/modelo/ContatoNaoExisteException.java @@ -1,10 +1,15 @@ package br.com.iagocolodetti.modelo; +/** + * + * @author iagocolodetti + */ public class ContatoNaoExisteException extends Exception { + public ContatoNaoExisteException() { super("Contato não existe."); } - + public ContatoNaoExisteException(String mensagem) { super(mensagem); } diff --git a/src/java/br/com/iagocolodetti/modelo/Usuario.java b/src/java/br/com/iagocolodetti/modelo/Usuario.java index d0fd2df..05a0c1b 100644 --- a/src/java/br/com/iagocolodetti/modelo/Usuario.java +++ b/src/java/br/com/iagocolodetti/modelo/Usuario.java @@ -1,25 +1,31 @@ package br.com.iagocolodetti.modelo; -public class Usuario { +/** + * + * @author iagocolodetti + */ +public class Usuario implements java.io.Serializable { + private static final long serialVersionUID = -1853712843268014785L; + private int id; private String nome, senha; public Usuario() { - + } - + public Usuario(String nome, String senha) { this.nome = nome; this.senha = senha; } - + public Usuario(int id, String nome, String senha) { this.id = id; this.nome = nome; this.senha = senha; } - + public int getId() { return id; } diff --git a/src/java/br/com/iagocolodetti/modelo/UsuarioDAO.java b/src/java/br/com/iagocolodetti/modelo/UsuarioDAO.java index 4497896..b9bb380 100644 --- a/src/java/br/com/iagocolodetti/modelo/UsuarioDAO.java +++ b/src/java/br/com/iagocolodetti/modelo/UsuarioDAO.java @@ -1,107 +1,13 @@ package br.com.iagocolodetti.modelo; -import br.com.iagocolodetti.controle.ConnectionFactory; -import br.com.iagocolodetti.controle.Util; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +/** + * + * @author iagocolodetti + */ +public interface UsuarioDAO { -public class UsuarioDAO { - - // Create - public void cadastrar(Usuario usuario) throws IllegalArgumentException, IndexOutOfBoundsException, UsuarioExisteException { - - if (usuario.getNome().contains(" ")) throw new IllegalArgumentException("Nome de usuário contém espaços."); - if (usuario.getNome().length() > 20) throw new IndexOutOfBoundsException("Nome de usuário contém mais que 20 caracteres."); - - if (usuario.getSenha().contains(" ")) throw new IllegalArgumentException("Senha contém espaços."); - if (usuario.getSenha().length() > 32) throw new IndexOutOfBoundsException("Senha contém mais que 32 caracteres."); - - if (usuarioExiste(usuario.getNome())) throw new UsuarioExisteException(); - - Connection con = ConnectionFactory.getConnection(); - - PreparedStatement ps = null; + public void cadastrar(Usuario usuario) + throws IllegalArgumentException, IndexOutOfBoundsException, UsuarioExisteException; - try { - ps = con.prepareStatement("INSERT INTO usuario(nome, senha) VALUES(?, ?)"); - ps.setString(1, usuario.getNome()); - ps.setString(2, Util.criptografar(usuario.getSenha())); - - ps.executeUpdate(); - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps); - } - } - - // Read - // Se o retorno do ID do usuário for -1, então o Usuário e a Senha não existem ou não coincidem. - public Usuario buscar(Usuario usuario) { - - usuario.setId(-1); - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; - ResultSet rs = null; - - try { - ps = con.prepareStatement("SELECT id, senha FROM usuario WHERE nome = ?"); - ps.setString(1, usuario.getNome()); - - rs = ps.executeQuery(); - - if (rs.next()) { - usuario.setId(rs.getInt("id")); - String criptografada = rs.getString("senha"); - - if (Util.verificarSenha(usuario.getSenha(), criptografada)) { - usuario.setSenha(""); - } - else { - usuario.setId(-1); - } - } - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps, rs); - } - - return usuario; - } - - private boolean usuarioExiste(String nome) { - - Connection con = ConnectionFactory.getConnection(); - PreparedStatement ps = null; - ResultSet rs = null; - - boolean existe = false; - - try { - ps = con.prepareStatement("SELECT id FROM usuario WHERE nome = ?"); - ps.setString(1, nome); - - rs = ps.executeQuery(); - - if (rs.next()) { - existe = true; - } - } - catch (SQLException e) { - e.printStackTrace(); - } - finally { - ConnectionFactory.closeConnection(con, ps, rs); - } - - return existe; - } + public Usuario buscar(Usuario usuario); } diff --git a/src/java/br/com/iagocolodetti/modelo/UsuarioDAOImpl.java b/src/java/br/com/iagocolodetti/modelo/UsuarioDAOImpl.java new file mode 100644 index 0000000..f34db7e --- /dev/null +++ b/src/java/br/com/iagocolodetti/modelo/UsuarioDAOImpl.java @@ -0,0 +1,89 @@ +package br.com.iagocolodetti.modelo; + +import br.com.iagocolodetti.controle.ConnectionFactory; +import br.com.iagocolodetti.controle.Util; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * + * @author iagocolodetti + */ +public class UsuarioDAOImpl implements UsuarioDAO { + + // Create + public void cadastrar(Usuario usuario) + throws IllegalArgumentException, IndexOutOfBoundsException, UsuarioExisteException { + + if (usuario.getNome().contains(" ")) { + throw new IllegalArgumentException("Nome de usuário contém espaços."); + } + if (usuario.getNome().length() > 20) { + throw new IndexOutOfBoundsException("Nome de usuário contém mais que 20 caracteres."); + } + + if (usuario.getSenha().contains(" ")) { + throw new IllegalArgumentException("Senha contém espaços."); + } + if (usuario.getSenha().length() > 32) { + throw new IndexOutOfBoundsException("Senha contém mais que 32 caracteres."); + } + + Connection con = ConnectionFactory.getConnection(); + + PreparedStatement ps = null; + + try { + ps = con.prepareStatement("INSERT INTO usuario(nome, senha) VALUES(?, ?)"); + ps.setString(1, usuario.getNome()); + ps.setString(2, Util.criptografar(usuario.getSenha())); + + ps.executeUpdate(); + } catch (SQLException e) { + if (e.getErrorCode() == 1062) { + throw new UsuarioExisteException(); + } else { + e.printStackTrace(); + } + } finally { + ConnectionFactory.closeConnection(con, ps); + } + } + + // Read + // Se o retorno do ID do usuário for -1, então o Usuário e a Senha não existem ou não coincidem. + public Usuario buscar(Usuario usuario) { + + usuario.setId(-1); + + Connection con = ConnectionFactory.getConnection(); + PreparedStatement ps = null; + ResultSet rs = null; + + try { + ps = con.prepareStatement("SELECT id, senha FROM usuario WHERE nome = ?"); + ps.setString(1, usuario.getNome()); + + rs = ps.executeQuery(); + + if (rs.next()) { + usuario.setId(rs.getInt("id")); + String criptografada = rs.getString("senha"); + + if (Util.verificarSenha(usuario.getSenha(), criptografada)) { + usuario.setSenha(""); + } else { + usuario.setId(-1); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + ConnectionFactory.closeConnection(con, ps, rs); + } + + return usuario; + } +} diff --git a/src/java/br/com/iagocolodetti/modelo/UsuarioExisteException.java b/src/java/br/com/iagocolodetti/modelo/UsuarioExisteException.java index d0de3cd..ebaa01d 100644 --- a/src/java/br/com/iagocolodetti/modelo/UsuarioExisteException.java +++ b/src/java/br/com/iagocolodetti/modelo/UsuarioExisteException.java @@ -1,10 +1,15 @@ package br.com.iagocolodetti.modelo; +/** + * + * @author iagocolodetti + */ public class UsuarioExisteException extends Exception { + public UsuarioExisteException() { super("Usuário já existe."); } - + public UsuarioExisteException(String mensagem) { super(mensagem); } diff --git a/web/agenda.jsp b/web/agenda.jsp index 9c06b88..1ae8aa4 100644 --- a/web/agenda.jsp +++ b/web/agenda.jsp @@ -1,3 +1,4 @@ + <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c"%> @@ -41,8 +42,8 @@ NOME EMAIL TELEFONE - ALTERAR - REMOVER + ALTERAR + REMOVER diff --git a/web/alterar.jsp b/web/alterar.jsp index ba79ac7..e1a9d99 100644 --- a/web/alterar.jsp +++ b/web/alterar.jsp @@ -1,3 +1,4 @@ + <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c"%> diff --git a/web/cadastrar.jsp b/web/cadastrar.jsp index 8d07800..f091f64 100644 --- a/web/cadastrar.jsp +++ b/web/cadastrar.jsp @@ -1,3 +1,4 @@ + <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c"%> diff --git a/web/css/estilos.css b/web/css/estilos.css index bd0807c..84a978f 100644 --- a/web/css/estilos.css +++ b/web/css/estilos.css @@ -1,3 +1,4 @@ +/* iagocolodetti */ body { background-color: rgb(245, 245, 245); } diff --git a/web/index.jsp b/web/index.jsp index fbe4497..7ec4106 100644 --- a/web/index.jsp +++ b/web/index.jsp @@ -1,3 +1,4 @@ + <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c"%> diff --git a/web/js/app.js b/web/js/app.js index ecc7db7..b41f63d 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -1,3 +1,6 @@ +/* iagocolodetti */ + +// Função 'sortTable' retirada e adaptada de: https://www.w3schools.com/howto/howto_js_sort_table.asp function sortTable(n) { var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0; table = document.getElementById("tabelaContato"); diff --git a/web/novo.jsp b/web/novo.jsp index bb0aa64..3de835f 100644 --- a/web/novo.jsp +++ b/web/novo.jsp @@ -1,3 +1,4 @@ + <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c"%>