Question about Filter - JSP

0

Well, I'm learning JSP and I'm trying to make a filter where the user is not logged in. It redirects to a login page, and I'm not getting it.

I created a Servlet controller that does the Dispacher for a JSP, in case it would be Add Task and List TaskLogic and these Logicas has the return to a JSP Page that is inside of WEB-INF / jsp / view

When trying to access a Logic by the URL eg: mvc? logica = Add Task it is redirecting to mvc? logica = Logging Screen "So far OK", but my page does not appear.

@WebServlet ("/ mvc") public class ControllerServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String parametro = request.getParameter("logica");

    if(parametro == null){
        throw new IllegalArgumentException("Falta passar o parametro.");
    }
    try {
        String nomeDaClasse = "br.com.triadworks.todoList.logica." + parametro;
        Class<?> classe = Class.forName(nomeDaClasse);
        Logica logica = (Logica) classe.newInstance();
        String pagina = logica.executa(request, response);
        request.getRequestDispatcher(pagina).forward(request, response);
    } catch (Exception e) {
        throw new ServletException("A lógica causou uma exceção!", e);
    }
}

}

public interface Logica {

String executa(HttpServletRequest request, HttpServletResponse response) throws Exception;

}

public class AddTag task implements Logica {

@Override
public String executa(HttpServletRequest request, HttpServletResponse response) {

    if (request.getSession().getAttribute("usuarioLogado") != null) {

        Connection connection = (Connection) request.getAttribute("connection");

        List<Usuario> usuarios = new UsuarioDAO(connection).buscarTodosUsuarios();
        List<Situacao> statusSituacao = Arrays.asList(Situacao.values());

        request.setAttribute("usuarios", usuarios);
        request.setAttribute("statusTarefas", statusSituacao);

        return "WEB-INF/jsp/view/adicionar.jsp";

    }
    return "mvc?logica=TelaLogin";
}

}

public class LoginTarefaLogic implements Logica {

@Override
public String executa(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Connection connection = (Connection) request.getAttribute("connection");

    String login = request.getParameter("usuario");
    String senha = request.getParameter("senha");

    Usuario usuarioAutenticado = new UsuarioDAO(connection).autenticar(new Usuario(login, senha));

    if (usuarioAutenticado != null) {
        System.out.println(request.getRequestURI());
        pegaSessaoUsuario(request, usuarioAutenticado);
        return "mvc?logica=AdicionaTarefa";
    } else {
        return "mvc?logica=TelaLogin";
    }
}

public static void pegaSessaoUsuario(HttpServletRequest request, Usuario usuarioAutenticado) {
    HttpSession session = request.getSession();
    session.setAttribute("usuarioLogado", usuarioAutenticado);
    System.out.println("Usuario: " +usuarioAutenticado.getNome() + "ID" + usuarioAutenticado.getId() + "senha: " +usuarioAutenticado.getSenha());
}

}

Filter

@WebFilter("/todoList/*")

public class FilterAuthenticator implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (verificaUsuarioLogado((HttpServletRequest) request)){
        System.out.println("verficando....");
        chain.doFilter(request, response);
    }else{
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendRedirect("index.jsp");
    }
}

private boolean verificaUsuarioLogado(HttpServletRequest servletRequest) {

    if (servletRequest.getSession().getAttribute("usuarioLogado") != null) {
        return true;
    } else {
        return false;
    }

}

}

    
asked by anonymous 14.11.2017 / 12:26

1 answer

0

The code seems a bit confusing as to what you want to do. From what I understood ...

You want a filter in the URL / * pattern, but there are some functions in / * that do not require a login. If so, change the url to another and do the mapping again. Example:

@WebFilter(filterName = "FilterLoggedIn", urlPatterns = {"/dash/*"}, dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE})
public class FilterLoggedIn implements Filter {

public boolean doBeforeProcessing(HttpServletRequest req) {

        if (req.getSession().getAttribute("user") == null) {
            return false;
        } else {
            return true;
        }
}

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        if (doBeforeProcessing((HttpServletRequest) request)) {
            chain.doFilter(request, response);
        } else {
            HttpServletResponse resp = (HttpServletResponse)response;
            resp.sendError(401);
        }

    }

}

Obviously, in your case you will change resp.sendError to sendRedirect , and the URL passed as parameter must be different from dash/* so that the filter does not try to capture the request again.

If you have any further questions, you can comment.

Hugs.

    
14.11.2017 / 15:30