简体   繁体   中英

dispatcher.forward causes infinite loop

I am trying to do the following: I create a servlet to handle all requests, and if the url contains the word "hello", then set the response code to 403, otherwise forward the request to an html page. Here is my servlet:

@WebServlet("/*")
public class AllRequestsHandlerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getRequestURL().toString();
        if(url.contains("hello")) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/static-html-page.html");
            dispatcher.forward(request, response);
        }
    }
}

But after forwarding, since this servlet handles the forwarded request too, it causes an infinite loop. How can I avoid that?

This will never work because /* maps to every request - including your forward to /static-html-page.html and path mappings take priority over all other mappings.

There are a couple of ways around this. The simplest (assuming no other content in the web app) would be:

  • rename /static-html-page.html to /static-html-page.jsp
  • change the mapping from /* to /

That does mean that /static-html-page.jsp would be directly accessible. If you don't want that, move it under /WEB-INF . request.getRequestDispatcher("/WEB-INF/static-html-page.html") will still work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM