theyuv
theyuv

Reputation: 1624

Get WebServlet name from Class name

Is there a way to get the @WebServlet name of a Servlet by using the class name?

I have access to the ServletContext if that helps.

The class name is safer to use because it gets refactored if I change it.

I'm trying to get a Servlet's mappings as follows

String servletName = "someServlet"   
Collection<String> mappings = servletContext.getServletRegistration(servletName).getMappings();

But rather than simply hard coding a value for the servletName I would prefer to retrieve it safely from the HttpServlet class.

Upvotes: 1

Views: 219

Answers (1)

BalusC
BalusC

Reputation: 1108912

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.

Upvotes: 2

Related Questions