0

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?

yrazlik
  • 10,411
  • 33
  • 99
  • 165
  • Check [this](https://stackoverflow.com/questions/7981026/requestdispatcher-ending-in-infinite-loop) as well as [here](https://stackoverflow.com/questions/48549551/tomcat-infinte-loop-on-requestdispatcherforward-stackoverflowerror) – Swati Jul 02 '19 at 06:47

1 Answers1

1

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.

Mark Thomas
  • 16,339
  • 1
  • 39
  • 60
  • Thanks, changing mapping from /* to / and renaming file from .html to .jsp worked, but why do I have to make my file a jsp file? If I leave my file extension as html, it still causes an infinite loop. – yrazlik Jul 03 '19 at 18:30
  • It comes down to which mapping takes precedence. JSPs are served by the JSP servlet that uses an extension mapping of *.jsp. Extension mappings are higher precedence than the default mapping. If you don't rename the html file it matches the default mapping so you get the infinite loop. Take a look at section 12.2 of the servlet spec and keep in mind the static files are normally served by Tomcat's default servlet which is mapped to `/`. – Mark Thomas Jul 03 '19 at 19:40