Solucionado (ver solução)
Solucionado
(ver solução)
4
respostas

Servlets fundamentos de Java na Web - Erro ao migrar Login

Pessoal, estou tentando migrar a classe Login de servlet para Tarefa e está dando o erro abaixo: HTTP Status 404 - /gerenciador/login

type Status report

message /gerenciador/login

description The requested resource is not available.

Apache Tomcat/7.0.73

Alguém pode me ajudar a identificar o problema ? Será que pode ser um problema no index.jsp ?Veja como está o meu código:

Login.java

package br.com.alura.gerenciador.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

import br.com.alura.gerenciador.Usuario;
import br.com.alura.gerenciador.dao.UsuarioDAO;

public class Login implements Tarefa {

    @Override
    public String executa(HttpServletRequest req, HttpServletResponse response) {
        String email = req.getParameter("email");
        String senha = req.getParameter("senha");
        Usuario usuario = new UsuarioDAO().buscaPorEmailESenha(email, senha);
        //PrintWriter writer = resp.getWriter();
        if(usuario == null) {
            return "/WEB-INF/paginas/loginInvalido.html";
        } else {
            HttpSession session = req.getSession();
            session.setAttribute("usuarioLogado", usuario);
            session.setMaxInactiveInterval(60);
            req.setAttribute("emailUsuario", usuario.getEmail());
            return "/WEB-INF/paginas/loginValido.jsp";
        }

    }

}

loginInvalido.html

<html>
<body>
Usuário ou senha inválida!
</body>
</html>

loginValido.jsp

<html>
<body>
Usuário ${usuario.email} logado!
</body>
</html>

Usuario.java

package br.com.alura.gerenciador;

public class Usuario {

    private String email;
    private String senha;

    public Usuario(String email, String senha) {
        this.email = email;
        this.senha = senha;
    }

    public String getSenha() {
        return senha;
    }

    public String getEmail() {
        return email;
    }

}

UsuarioDAO.java

package br.com.alura.gerenciador.dao;

import java.util.HashMap;
import java.util.Map;

import br.com.alura.gerenciador.Usuario;

public class UsuarioDAO {

    private final static Map<String, Usuario> USUARIOS = new HashMap<>();
    static {
        USUARIOS.put("guilherme.silveira@alura.com.br", new Usuario("guilherme.silveira@alura.com.br","silveira"));
        USUARIOS.put("rodrigo.turini@alura.com.br", new Usuario("rodrigo.turini@alura.com.br","turini"));
    }

    public Usuario buscaPorEmailESenha(String email, String senha) {
        if (!USUARIOS.containsKey(email))
            return null;

        Usuario usuario = USUARIOS.get(email);
        if (usuario.getSenha().equals(senha))
            return usuario;

        return null;
    }

}

index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
Bem vindo ao nosso gerenciador de empresas!<br/>

<c:if test="${not empty usuarioLogado}">
    Logado como ${usuarioLogado.email}<br/>
</c:if>

<form action="fazTudo?tarefa=NovaEmpresa" method="post">
    Nome: <input type="text" name="nome" /><br />
    <input type="submit" value="Enviar" />
</form>
<form action="login" method="POST">
    Email: <input type="email" name="email" />
    Senha: <input type="password" name="senha" />
    <input type="submit" value="Enviar" />
</form>
<form action="fazTudo" method="POST">
    <input type="hidden" name="tarefa" value="Logout" />
    <input type="submit" value="Deslogar" />
</form>
</body>
</html>
4 respostas

Bom dia Mario, este erro : HTTP Status 404 - /gerenciador/login significa que quem deveria chamar seu Login não está achando o caminho /gerenciador/login. Pode colar aqui a servlet que recebe as requisições e quem está mapeado para /gerenciador/login por favor?

Olá Guilherme, Sou novo no Java. Estou meio perdido. A servlet que recebe as requisições seria uma das classes do projeto? Eu tenho um endereço inicial: http://localhost:8080/gerenciador/ Que quando chamado executa a página index.jsp, que eu mostrei o código acima. Nesta pagina inicial eu digito o login (email) e a senha e clico em Enviar. Neste ponto acontece o erro. Vou colocar o código da classe FazTudo.java ne a interface Tarefa.java, que talvez sejam as informações que estão faltando.

Faz tudo.java

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;

@WebServlet(urlPatterns="/fazTudo")
public class FazTudo extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        String tarefa = req.getParameter("tarefa");
        //qual tarefa exatamente?
        if(tarefa == null) {
            throw new IllegalArgumentException(
                                 "Você esqueceu de passar a tarefa");
        }
        tarefa = "br.com.alura.gerenciador.web." + tarefa;

        try {
            Class<?> tipo = Class.forName(tarefa);
            Tarefa instancia = (Tarefa) tipo.newInstance();
            String pagina = instancia.executa(req, resp);
            RequestDispatcher dispatcher = req.getRequestDispatcher(pagina);
            dispatcher.forward(req, resp);
        } catch (ClassNotFoundException | InstantiationException 
                | IllegalAccessException e) {
            throw new ServletException(e);
        }

    }

}

Tarefa.java

package br.com.alura.gerenciador.web;

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

public interface Tarefa {

    String executa(HttpServletRequest req, HttpServletResponse response);

}
<form action="login" method="POST">

Para isso, você precisa ter uma servlet mapeada com /login, seja no web.xml ou com @WebServlet, você tem ?

solução!

Guilherme, consegui resolver. O código para o login ficou da seguinte forma:

Efetuando Login<br/>
<form action="fazTudo?tarefa=Login" method="POST">
    Email: <input type="email" name="email" />
    Senha: <input type="password" name="senha" />
    <input type="submit" value="Enviar" />
</form>