javajsptomcatservletsservlet-container

how does Tomcat serve different applications with in the same servlet container?


My question is based on understanding of how webserver - servlet container interacts. So please correct me if my basic understanding is wrong.

  1. consider a request coming in: www.bank.com/credit-cards.

  2. As soon as the Tomcat Server gets the request, it forwards it to the servlet Container whose web.xml maps to the incoming URI which is /credit-cards above

  3. Servlet Container does its routine of instantiating the servlet (if this the first request). if not, it will create a Thread for this request and hands it over to Servlet, which handles generating the response. Tomcat then returns the response to client browser.

  4. Now suppose I have another request at www.bank.com/accounts. This is served by a different application with-in the same server. It is NOT a different servlet with in the same application.

  5. Now how is the url-mapping kept? How does the server knows which application it should forward the request to? The server does not hold any descriptor files. Application 1 and Application 2 has web.xml files that maps the incoming the url to servlets. Does all the URL-mapping and servlets gets registered somewhere in the server for a look up?

  6. I guess each application should have its own container. That is there will be two servlet containers in the above case.

  7. Is this a common scenario? I don't know any real world examples where servlets/JSPs are used that holds mulitple applications with in a server (probably a user cannot differentiate if the two request come from the same or different appications anyway)


Solution

  • Each applications has its own folder under webapps.

    The application credit-cards is under .../webapps/credit-cards/.

    The application accounts is under .../webapps/accounts/.

    Any file directly on the server root in the URL, like http://localhost:8080/index.jsp is under the root application in the folder .../webapps/ROOT/. That's how Tomcat knows.

    Servlet mappings within each folder's ./WEB-INF/web.xml map the servlet underneath the application.

    Where you could get into trouble is if you created folders under .../webapps/ROOT/ or mapped servlets there that would conflict with the URL of another application.

    Edit: As Bruno pointed out in a comment, this answer only applies when auto deployment is on.