Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Login utilizando Controller #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@ Bem vindo ao curso Servlet 3 e fundamentos Web da Alura

http://www.alura.com.br/cursos-online-java/servlet-3-e-fundamentos-web


jvmarquesvm - 19/01/2017 - Curso Completo de servlet-3-e-fundamentos-web - Alura
Contribuicao: utilizando Controller na acao de login. e nos demais arquivos mostrando a evolucao.

8 changes: 8 additions & 0 deletions gerenciador/WebContent/WEB-INF/paginas/ErrorLogin.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>Erro no Login</title>
</head>
<body>
Nao foi possivel se conectar. Senha ou Usuario Invalidos!
</body>
</html>
8 changes: 8 additions & 0 deletions gerenciador/WebContent/WEB-INF/paginas/SucessLogin.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>Usuario logado com sucesso!</title>
</head>
<body>
Usuario logado com sucesso!!
</body>
</html>
15 changes: 15 additions & 0 deletions gerenciador/WebContent/WEB-INF/paginas/buscaEmpresa.jsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Busca de Empresas</title>
</head>
<body>

Resultado da Busca:
<ul>
<c:forEach var="empresa" items="${empresas}">
<li>${empresa.id}: ${empresa.nome}</li>
</c:forEach>
</ul>
</body>
</html>
10 changes: 10 additions & 0 deletions gerenciador/WebContent/WEB-INF/paginas/logout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Out</title>
</head>
<body>
Usuário deslogado com sucesso!
</body>
</html>
8 changes: 8 additions & 0 deletions gerenciador/WebContent/WEB-INF/paginas/novaEmpresa.jsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>Adicionar Empresa</title>
</head>
<body>
Empresa ${empresa.nome} adicionada com sucesso!!!
</body>
</html>
22 changes: 7 additions & 15 deletions gerenciador/WebContent/WEB-INF/web.xml
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>gerenciador</display-name>

<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>gerenciador</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
31 changes: 31 additions & 0 deletions gerenciador/WebContent/index.jsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:if test="${not empty usuarioLogado }">
Logado como ${usuarioLogado.email}<br />
</c:if>

Bem-vindo ao nosso gerenciador de empresas!
<br />
<form action="executa?tarefa=NovaEmpresa" method="post" >
Nome: <input type="text" name="nomeEmp">
<input type="submit" value="Enviar">
</form>

<form action="executa?tarefa=Login" method="post">
Email: <input type="text" name="email">
</br>
Senha: <input type="password" name="senha">
</br>
<input type="submit" value="Login">
</form>

<!-- Refatoramento de codigo -->
<!-- <form action="logout" method="post"> -->
<!-- <form action="FazTudo?tarefa=Logout" method="post"> -->
<form action="executa" method="post">
<input type="hidden" name="tarefa" value="Logout">
<input type="submit" value="Logout">
</form>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class UsuarioDAO {
static {
USUARIOS.put("[email protected]", new Usuario("[email protected]","silveira"));
USUARIOS.put("[email protected]", new Usuario("[email protected]","turini"));
USUARIOS.put("[email protected]", new Usuario("[email protected]","marques"));
}

public Usuario buscaPorEmailESenha(String email, String senha) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package br.com.alura.gerenciador.interfaces;

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

public interface Tarefa {
String executa(HttpServletRequest req, HttpServletResponse res);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package br.com.alura.gerenciador.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.alura.gerenciador.Empresa;
import br.com.alura.gerenciador.dao.EmpresaDAO;
import br.com.alura.gerenciador.interfaces.Tarefa;

//Modificacao para refatorar o codigo
//@WebServlet(urlPatterns="/busca")
//public class BuscaEmpresa extends HttpServlet{
public class BuscaEmpresa implements Tarefa {
///**
// *
// */
//private static final long serialVersionUID = 1L;
//Testando a concorrencia de recursos
//String filtro = "";

@Override
public String executa(HttpServletRequest req, HttpServletResponse res) {
String filtro = req.getParameter("filtro");
EmpresaDAO empresaDAO = new EmpresaDAO();
Collection<Empresa> emps = empresaDAO.buscaPorSimilaridade(filtro);
req.setAttribute("empresas", emps);
return "/WEB-INF/paginas/buscaEmpresa.jsp";
}

//Modificacao para refatorar o codigo - nao e mais um servlet
/*public BuscaEmpresa() {
System.out.println("Instanciando uma Servlet do tipo BuscaEmpresa " + this);
}*/

//Modificacao para refatorar o codigo - nao e mais um servlet
/*@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException{
PrintWriter wr = resp.getWriter();
String filtro = req.getParameter("filtro");

//Testando a concorrencia de recursos
filtro = req.getParameter("filtro");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
} // tempo em milisegundos

EmpresaDAO empresaDAO = new EmpresaDAO();
Collection<Empresa> emps = empresaDAO.buscaPorSimilaridade(filtro);

//Utilizando o writer para escrever a página
wr.println("<html>");
wr.println("<body>");
wr.println("Resultado da Busca: ");
wr.println("<ul>");
for (Empresa empresa : emp){
wr.println("<li>"+ empresa.getId() + ": " + empresa.getNome() + "</li>" );
}
wr.println("</ul>");
wr.println("</body>");
wr.println("</html>");

//Redirecionando do lado do servidor
req.setAttribute("empresas", emps);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/paginas/buscaEmpresa.jsp");
requestDispatcher.forward(req, resp);
}*/

//Modificacao para refatorar o codigo - nao e mais um servlet
/*@Override
public void init() throws ServletException {
super.init();
System.out.println("Inicializando a Servlet " + this);
}*/

//Modificacao para refatorar o codigo - nao e mais um servlet
/*@Override
public void destroy() {
super.destroy();
System.out.println("Destruindo a Servlet " + this);
}*/
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package br.com.alura.gerenciador.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.alura.gerenciador.interfaces.Tarefa;


/**
* Servlet implementation class Controller - Pegar todas as requisicoes e redirecionar
*/
@WebServlet(description = "Servlet resposável pegar todas as requisições", urlPatterns = { "/executa" })
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//tarefa e o nome da classe no pacote web
//Qual Tarefa?
//Para tnde redirecionar?
// URI /Controller?tarefa=<nomedaclasse>
String tarefa = request.getParameter("tarefa");
if(tarefa == null){
throw new IllegalArgumentException("Acao nao foi passada!");
}
String classeNome = "br.com.alura.gerenciador.web." + tarefa;
Class<?> tipo = Class.forName(classeNome);
Tarefa instancia = (Tarefa)tipo.newInstance();
String pagina = instancia.executa(request, response);
RequestDispatcher dispatcher = request.getRequestDispatcher(pagina);
dispatcher.forward(request, response);
} catch (ClassNotFoundException e) {
throw new ServletException();
} catch (InstantiationException e) {
throw new ServletException();
} catch (IllegalAccessException e) {
throw new ServletException();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package br.com.alura.gerenciador.web;

import javax.servlet.http.Cookie;

public class Cookies {

private final Cookie[] cookies;

public Cookies(Cookie[] cookies) {
this.cookies = cookies;
// TODO Auto-generated constructor stub
}

public Cookie buscarUsuarioLogado() {
if(cookies != null){
for (Cookie cookie : cookies){
if( cookie.getName().equals("usuarioLogado")){
return cookie;
}
}
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package br.com.alura.gerenciador.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.alura.gerenciador.Usuario;

@WebFilter(urlPatterns="/*")
public class FiltroDeAuditoria implements Filter {


@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest requisicao = (HttpServletRequest)req;
HttpServletResponse resposta = (HttpServletResponse)resp;
//Buscando usuário utilizando cookie
//String usuario = getUsuarioCookie(requisicao, resposta);
//Buscando usuário utilizando a session
HttpSession session = requisicao.getSession();
Usuario usuarioLogado = (Usuario) session.getAttribute("usuarioLogado");
String usuario = "<deslogado>";
if(usuarioLogado != null){
usuario = usuarioLogado.getEmail();
}
System.out.println("Usuario " + usuario + " acessando a URI - " + requisicao.getRequestURI());
chain.doFilter(req, resp);
}

/**
* @param requisicao
* @return
*/
private String getUsuarioCookie(HttpServletRequest requisicao, HttpServletResponse resposta) {
/*String usuario = "<deslogado>";
Cookie[] cookies = requisicao.getCookies();
if(cookies != null){
for (Cookie cookie : cookies){
if( cookie.getName().equals("usuario.logado")){
cookie.setMaxAge(60); //Tempo em segundos
// resp.addCookie(cookie); //Reescrevendo o cookie no browser
usuario = cookie.getValue();
}
}
}
return usuario; */ //Código Reescrito para logout
String retorno = "";
Cookie cookie = new Cookies(requisicao.getCookies()).buscarUsuarioLogado();
if (cookie == null){
retorno = "<deslogado>";
} else{
//Atualizando o tempo do cookie após cada requisição
cookie.setMaxAge(60); //Tempo em segundos
resposta.addCookie(cookie);
retorno = cookie.getValue();
}

return retorno;
}

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

}

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}
}
Loading