Search code examples
javatomcatservletsweb.xmlservlet-mapping

Accessing URL mappings of a servlet in Tomcat with only static functions


I need to use URL-mapping for my servlet which is set in web.xml. Currently I can read the mappings with the following code in the processRequest function.

Iterator<String> urlMappings = this.getServletContext().getServletRegistration(MyServletClass.class.getSimpleName()).getMappings().iterator();
while (urlMappings.hasNext()) {
    System.out.println(urlMappings.next());
}

However getServletContext function is not static and therefore I cannot read it without an instance of the servlet. That is also OK but if there is a way to do this with only static functions I will prefer that solution. Any help?

I am using Tomcat 8.0.3 and JDK 1.8


Solution

  • Add a ServletContextListener to your web.xml. This will be called when your webapp is loaded. In the contextInitialized() method you can store the ServletContext in a static variable for example for later use. Then you will be able to access the ServletContext in a static way:

    class MyListener implements ServletContextListener {
    
        public static ServletContext context;
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            context = sce.getServletContext();
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            context = null;
        }
    
    }
    

    Add it to web-xml like this:

    <web-app>
        <listener>
            <listener-class>
                com.something.MyListener
            </listener-class>
        </listener>
    </web-app>
    

    And you can access it from anywhere like this:

    MyListener.context.getServletRegistration(
        MyServletClass.class.getSimpleName()).getMappings().iterator();
    

    Note:

    You might want to store it as private and provide a getter method, and also check for null value before using it.