servlet过滤器不起作用

ffvjumwh  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(577)

这个问题在这里已经有答案了

java.lang.illegalstateexception:提交响应后无法(转发| sendredirect |创建会话)(8个答案)
四天前关门了。
我正在尝试编写一个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;
    }
}

为什么?这两个代码之间的区别是什么?其中一个代码在运行我的程序时会导致问题。
谢谢。

mqkwyuun

mqkwyuun1#

在返回的第一个(非工作)代码中 RequestDispatcher#forward() 然后继续 chain.doFilter() ,而在第二个(工作)代码中,您可以执行其中一个操作,但不能同时执行两个操作。

相关问题