Servlet filter mapped on /* results in browser error “server is redirecting the request for this address in a way that will never complete”

一曲冷凌霜 提交于 2020-01-05 07:22:10

问题


I am developing a dynamic JSP/Servlet web application. In order to handle the session, I am using a filter which is mapped on /* in web.xml. When I'm opening a page in Firefox, it gives the following Firefox-specific error message:

Firefox has detected that the server is redirecting the request for this address in a way that will never complete

A similar error is shown in Chrome. How is this caused and how can I solve it?


回答1:


Your filter is redirecting to an URL which is invoking the very same filter with the very same conditions again which in turn thus results in a new redirect, etcetera. Your filter is basically redirecting to itself in an infinite loop. The webbrowser is blocking the infinite loop after ~20 requests to save the enduser from badly designed webapplications.

You need to fix your filter accordingly that it is not performing a redirect when it has already been performed. Let's assume a basic real world example of a login filter which is mapped on /* which should be redirecting to the login page when the user is not logged in which is identified by user attribute in session. You obviously want that the filter should not redirect to the login page if the login page itself is currently been requested.

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String loginURL = request.getContextPath() + "/login.jsp";

        boolean loggedIn = session != null && session.getAttribute("user") != null;
        boolean loginRequest = request.getRequestURI().equals(loginURL);

        if (loggedIn || loginRequest) {
            chain.doFilter(request, response); // Logged-in user found or already in login page, so just continue request.
        } else {
            response.sendRedirect(loginURL); // No logged-in user found and not already in login page, so redirect to login page.
        }
    }

    // ...
}

You see, if you want to allow/continue a request, just call chain.doFilter() instead of response.sendRedirect(). Use redirect only if you want to change a request to a different destination.



来源:https://stackoverflow.com/questions/13791577/servlet-filter-mapped-on-results-in-browser-error-server-is-redirecting-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!