Search code examples
javaservletsjakarta-eeweb.xmlurl-pattern

Get url-pattern from servlet-name


I have this configuration in web.xml fileof my Java EE Web application:

<servlet-mapping>
   <servlet-name>ChangeLanguageServlet</servlet-name>
   <url-pattern>/change</url-pattern>
</servlet-mapping>

What I want to do is get the String of "url-pattern" using the servlet-name, something like this (pseudocode):

// This would return "/change"
String pattern = getPatternByServletName("ChangeLanguageServlet"); 

I don't know how to do it.

Any help?

Thanks!


Solution

  • From the ServletContext you can get a Map keyed by servlet name with all servlets registered in the application:

    Map<String, ? extends ServletRegistration> registrations = 
            servletContext.getServletRegistrations();
    

    Then use the ServletRegistration API to extract the metadata you need, including: