Runtime Discovery of Servlet Mappings

When a Servlet is activated, the mapping info can be discoverable at runtime.

Described in the Servlet specification.

The method getHttpServletMapping() on HttpServletRequest returns an HttpServletMapping implementation that provides information for the mapping that caused the current Servlet to be invoked. Please see the javadocs for the normative specification. Please see sections Section 9.3.1, “Included Request Parameters” on page 9-101Section 9.4.2, “Forwarded Request Parameters” on page 9-102 and Section 9.7.2, “Dispatched Request Parameters” on page 9-104 for relevant request attributes.

But please notice:

As with the included and forwarded request parameters, the HttpServletMapping is not available for servlets that have been obtained with a call to ServletContext.getNamedDispatcher().

An sample to print the mapping information of a Servlet .

@WebServlet(name = "MyServlet",
        urlPatterns = {
            "/MyServlet",
            "/",
            "/path/*",
            "*.extension"
        }
)
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {


        HttpServletMapping mapping = request.getHttpServletMapping();

        response.getWriter()
                .append("Mapping match:")
                .append(mapping.getMappingMatch().name())
                .append("\n")
                .append("Match value:")
                .append(mapping.getMatchValue())
                .append("\n")
                .append("Pattern:")
                .append(mapping.getPattern());
    }
}

Here is an example for demonstrating forward, async dispatch, and include.

Try to access ServletA with different urls(urlPatterns of WebServlet annotation on ServletA), which results in different mappings.

Grab the source codes from my GitHub account, and have a try.

Last updated

Was this helpful?