在将 For 循环提取到方法之前,Servlet 过滤器不起作用

Servlet Filters does not work before extracting a For loop to a method

我正在尝试编写一个 servlet 过滤器来拦截所有需要登录的请求。

这是我的过滤器:

@WebFilter(filterName = "LoginNeedCustomerFilter", urlPatterns = "/*")
public class LoginNeedCustomerFilter implements Filter {

    private FilterConfig filterConfig;
    private static final String[] needToLoginUrls = {"/view_profile", "/edit_profile", "/update_profile",
            "/write_review", "/checkout", "/place_order", "/view_orders", "/show_order_detail"};


    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession existedSession = request.getSession(false);

        String contextPath = filterConfig.getServletContext().getContextPath();
        String requestURI = request.getRequestURI();

        if (requestURI.startsWith(contextPath + "/admin/")) {

            chain.doFilter(req, resp);
            return;
        }

        boolean isLoggedIn = (existedSession != null) && (existedSession.getAttribute("theCustomer") != null);

        if (!isLoggedIn) {

            for (String loginRequiredURL : needToLoginUrls) {
                if (requestURI.contains(loginRequiredURL)) {

                    String destination = "frontend/login.jsp";
                    RequestDispatcher dispatcher = req.getRequestDispatcher(destination);
                    dispatcher.forward(req, resp);
                }

            }
        }
        
        chain.doFilter(req, resp);
    }


    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }
}

但是此代码不起作用并抛出此异常:

05-Jan-2021 04:53:24.040 SEVERE [http-nio-8080-exec-14] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [ShowEditProfileFormServlet] in context with path [/MehdiSarfBookStore_war_exploded] threw exception
    java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
        at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:456)
        at javax.servlet.http.HttpServlet.doGet(HttpServlet.java:174)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at com.mehdisarf.mehdisarfbookstore.controller.frontend.customer.LoginNeedCustomerFilter.doFilter(LoginNeedCustomerFilter.java:56)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at com.mehdisarf.mehdisarfbookstore.controller.frontend.category.GetCategoriesFilter.doFilter(GetCategoriesFilter.java:36)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:844)

但是 当我将for 循环提取到一个方法中,并更改outter if 的条件时,一切都会好的。像这样:

@WebFilter(filterName = "LoginNeedCustomerFilter", urlPatterns = "/*")
public class LoginNeedCustomerFilter implements Filter {

    private FilterConfig filterConfig;
    private static final String[] needToLoginUrls = {"/view_profile", "/edit_profile", "/update_profile",
            "/write_review", "/checkout", "/place_order", "/view_orders", "/show_order_detail"};


    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpSession existedSession = request.getSession(false);

        String contextPath = filterConfig.getServletContext().getContextPath();
        String requestURI = request.getRequestURI();

        if (requestURI.startsWith(contextPath + "/admin/")) {

            chain.doFilter(req, resp);
            return;
        }

        boolean isLoggedIn = (existedSession != null) && (existedSession.getAttribute("theCustomer") != null);


        if (!isLoggedIn && this.isLoginRequired(requestURI)) {


            String destination = "frontend/login.jsp";
            RequestDispatcher dispatcher = req.getRequestDispatcher(destination);
            dispatcher.forward(req, resp);

        } else {
            chain.doFilter(req, resp);
        }
    }

    private boolean isLoginRequired(String requestURL) {
        for (String loginRequiredURL : needToLoginUrls) {
            if (requestURL.contains(loginRequiredURL)) {
                return true;
            }
        }
        return false;
    }

    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
    }
}

为什么?这两个代码之间有什么区别,其中一个会导致 运行 我的程序出现问题。

谢谢。

在第一个(非工作)代码中,您从 RequestDispatcher#forward() return 继续到 chain.doFilter(),而在第二个(工作)代码中,您执行一个或另一个但不是两者。