How can I map a url-pattern ending .jsp to a servlet?

I’d like a map a URL that used to point to a JSP directly onto a servlet, but my efforts so far – mapping the following url pattern to my servlet…

<url-pattern>/folder/myoldjsp.jsp</url-pattern>

have failed, causing a JSP processing error to be returned to the client. How can I map a URL ending .jsp to my servlet?

Answer

It should work fine if your servlet is not in turn forwarding the request to the JSP in question. This would namely have resulted in an infinite dispatch loop as the servlet itself would be executed again on the RequestDispatcher#forward() call.

If renaming the target JSP file is not an option for some reason, then your best bet is to map the servlet on a different URL pattern like /foo and create a filter mapped on /folder/* (or whatever matches the request URL(s) closest) which in turn determines if the HttpServletRequest#getRequestURI() ends with /myoldjsp.jsp and then forwards the request to the servlet.

E.g.

if (((HttpServletRequest) request).getRequestURI().endsWith("/myoldjsp.jsp")) {
    request.getRequestDispatcher("/foo").forward(request, response);
} else {
    chain.doFilter(request, response);
}

Filters are namely by default not invoked on forwarded requests. You could if necessary make the JSP file name(s) configureable as filter <init-param>.

Leave a Reply

Your email address will not be published. Required fields are marked *