1

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

sancho
  • 598
  • 2
  • 8
  • 22

2 Answers2

1

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.
Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43
  • P.Karwasz thanks for detailed answer. I removed `ROOT` context then whenever I call `getContext("/app2")` it returns `null`. But if `ROOT` context exists then `getContext` return `ROOT` as you wrote. Maybe I misunderstood the documentation or maybe was not clarified this situation – sancho Jan 12 '22 at 08:12
0

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

  • but documentation said that `the ServletContext object that corresponds to the named URL, or null if either none exists or the container wishes to restrict this access.` in this case it should return `null` if context not exists – sancho Jan 11 '22 at 10:24
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 11 '22 at 10:49