Issue
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.
Solution
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
.
Answered By - BalusC
Answer Checked By - Mary Flores (JavaFixing Volunteer)