Why Servlet.getContext(String) does not return null after undeploy

Viewed 55

I am using tomcat-10(jakarta). According to the doc getContext(String) return null if context not exists or restricted access. But in practice is not correct. For example I have two web application with /app1 and /app2. After running I undeploy /app2. I also checked registered MBeans with JMX and there is no registered servlet with context /app2. But when I call getContext(/app2) it returns ROOT servlet. Is it a bug or works normally?

UPDATE For testing I just remove tomcat default ROOT web application. After removing when I call getContext method I got null if the requested context not exists. So that I think there is some missing information on the documentation or the custom implementation of Servlet

2 Answers

The parameter to ServletContext#getContext does not need to point to the exact URI of the context. Therefore:

  • all strings that start with /app1 will give you the context for the /app1 application,
  • all strings that start with /app2 will give you the context for the /app2 application,
  • after you stop /app2, all requests for /app2 will be routed to the ROOT context. Therefore getContext("/app2") will return the ROOT context.

The getContext method is to get the reference to servlet context for different web applications and will not null if your current application does have permission to access other contexts as specified by the defaults of tomcat i.e. cross-context = true.

Also, your current web app already has a reference to the servlet context may be in your application variable

Related