Doubt about Filter - JSP

Asked

Viewed 119 times

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.

NOTE: I created a controller Servlet that makes Dispacher for a JSP, in Case it would be Add task and Listartarefalogic and these Logicas have the return to a JSP Page that is within WEB-INF/jsp/view

When trying to access a Logic from the URL ex: mvc? logica=Added task it is redirecting to mvc? logica=Teladelogin "So far OK", only that 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 Added task Logica Mplements {

@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;
    }

}

}

  • Put the Servlet code that calls the JSP from the login screen.

  • Okay, I put the login screen where the user’s session is stored, in this case it is working normally. In the case of Logica **Add task ** I am doing if there is Sesssion to continue accessing, my doubt is using Filter.

  • Your filter is apparently correct with respect to redirect. I will post a filter that I have and that works very well. It may be that when giving the redirect, it enters the filter again and again and again, since the urlPattern is to /*

1 answer

0

The code seems a little confusing with what you want to do. From what I understand...

You want a filter in the /* URL pattern only there are some /* functions that do not require login. If this is the case, 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 will change the resp.sendError for 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, please comment.

Hugs.

  • These Dispatchertype is not recognized.

  • This is from the Servlet 3.1 specification. Try removing or searching for something equivalent to your version.

  • I put it like this, nothing yet..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.