Issue
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?
Solution
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.
Answered By - Mark Thomas