How to redirect in a servlet filter?

前端 未结 5 524
孤街浪徒
孤街浪徒 2020-12-01 08:52

I\'m trying to find a method to redirect my request from a filter to the login page but I don\'t know how to redirect from servlet. I\'ve searched but what I find is s

相关标签:
5条回答
  • 2020-12-01 09:24

    Your response object is declared as a ServletResponse. To use the sendRedirect() method, you have to cast it to HttpServletResponse. This is an extended interface that adds methods related to the HTTP protocol.

    0 讨论(0)
  • 2020-12-01 09:25

    In Filter the response is of ServletResponse rather than HttpServletResponse. Hence do the cast to HttpServletResponse.

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.sendRedirect("/login.jsp");
    

    If using a context path:

    httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");
    

    Also don't forget to call return; at the end.

    0 讨论(0)
  • 2020-12-01 09:29

    I'm trying to find a method to redirect my request from filter to login page

    Don't

    You just invoke

    chain.doFilter(request, response);
    

    from filter and the normal flow will go ahead.

    I don't know how to redirect from servlet

    You can use

    response.sendRedirect(url);
    

    to redirect from servlet

    0 讨论(0)
  • 2020-12-01 09:33

    If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):

    String uri = request.getRequestURI();
    
    String[] uriParts = uri.split("[#?]");
    String path = uriParts[0];
    String rest = uri.substring(uriParts[0].length());
    
    if(redirectMap.containsKey(path)) {
        response.sendRedirect(redirectMap.get(path) + rest);
    } else {
        chain.doFilter(request, response);
    }
    
    0 讨论(0)
  • 2020-12-01 09:37

    Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

    if (response instanceof HttpServletResponse) {
        response.sendRedirect(....);
    }
    
    0 讨论(0)
提交回复
热议问题