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
Add a ServletContextListener to your
web.xml
. This will be called when your webapp is loaded. In thecontextInitialized()
method you can store theServletContext
in a static variable for example for later use. Then you will be able to access theServletContext
in a static way:Add it to
web-xml
like this:And you can access it from anywhere like this:
Note:
You might want to store it as
private
and provide agetter
method, and also check fornull
value before using it.