Issue
I'm trying to write a servlet filter that intercepts to all requests that need login.
This is My Filter:
@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;
}
}
but this code does not work and throw this exception:
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)
But when I extract the for
loop to a method, and change the condition of outter if
, everythings will be ok. like this:
@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;
}
}
why? what is the difference between these two code that one of them will cause problem in running my program.
Thanks.
Solution
In the first (non-working) code you return from RequestDispatcher#forward()
and continue on to chain.doFilter()
, while in the second (working) code you do one or the other but not both.
Answered By - Jim Garrison
Answer Checked By - Marie Seifert (JavaFixing Admin)