Get WebServlet name from Class name

Solution 1:

The ServletContext has another method which returns all servlet registrations: getServletRegistrations(). The ServletRegistration interface has in turn a getClassName() method which is of your interest:

String getClassName()

Gets the fully qualified class name of the Servlet or Filter that is represented by this Registration.

So, this should do:

Class<? extends HttpServlet> servletClass = YourServlet.class;
Optional<? extends ServletRegistration> optionalRegistration = servletContext
    .getServletRegistrations().values().stream()
    .filter(registration -> registration.getClassName().equals(servletClass.getName()))
    .findFirst();

if (optionalRegistration.isPresent()) {
    ServletRegistration registration = optionalRegistration.get();
    String servletName = registration.getName();
    Collection<String> servletMappings = registration.getMappings();
    // ...
}

The servletName is your answer. But as you can see, the mappings are readily available without the need for yet another ServletContext#getServletRegistration() call with the servletName.