简体   繁体   English

Tomcat 如何知道选择哪个 jar 来运行 servlet?

[英]How does Tomcat know which jar to choose for running a servlet?

In my project, Apache Tomcat 8.5 context.xml is configured as follows.在我的项目中, Apache Tomcat 8.5 context.xml配置如下。

<Context path="/helloWorld" docBase="C:\projects\helloWorld\app" crossContext="false" debug="0" reloadable="false"/>

C:\projects\helloWorld\app has a web-inf\lib folder which contains a servlet.jar along with the rest of the jars that the application needs. C:\projects\helloWorld\app 有一个 web-inf\lib 文件夹,其中包含一个servlet.jar以及应用程序需要的 jars 的 rest。

This application is deployed to a Tomcat 8.5 web server and %TOMCAT_HOME%\lib folder also contains a servlet-api.jar .此应用程序部署到 Tomcat 8.5 web 服务器,%TOMCAT_HOME%\lib 文件夹还包含一个servlet-api.jar

The application is working as expected.该应用程序按预期工作。

I have checked the two jars and servlet.jar contains the regular servlet api classes whereas tomcat's servlet-api.jar contains these regular servlet api classes along with many other servlet functionality related classes.我检查了两个 jars 和 servlet.jar 包含常规 servlet api 类,而 tomcat 的 servlet-api.jar 包含这些常规 servlet api 类以及许多其他 servlet 功能相关类。

Query: Since there are two jars for running a servlet viz, servlet.jar and servlet-api.jar, how does Tomcat know which jar to pick up when running a servlet?查询:因为有两个 jars 用于运行 servlet,即 servlet.jar 和 servlet-api.jar,Tomcat 如何知道在运行 servlet 时选择哪个 jar?

TLDR: TLDR:

Tomcat will load its own version of the servlet API, because this is required by the JavaEE specification. Tomcat 将加载自己版本的 servlet API,因为这是 JavaEE 规范所要求的。

The long answer长答案

JavaEE defines how classes are loaded and resolved. JavaEE 定义了如何加载和解析类。

Usually class-loaders are parent-first - ie trying to load classes from the parent class-loader and only if that fails, they try to load the class themselves.通常类加载器是父级优先的——即尝试从父类加载器加载类,只有在失败时,它们才会尝试自己加载 class。

But web apps have a self-first class-loader which loads classes from itself and only if it fails then they try to load from the parent.但是 web 应用程序有一个自优先类加载器,它从自身加载类,只有当它失败时,它们才会尝试从父类加载。 But there are a few exceptions:但也有一些例外:

  • those self-first class-loaders cannot override JRE classes那些自我优先的类加载器不能覆盖 JRE 类
  • and they always do "parent-first" loading of JavaEE classes并且他们总是“父优先”加载 JavaEE 类

You can read about that in more details on the Apache Tomcat's docs您可以在Apache Tomcat 的文档中阅读更多详细信息

As long as the servlet api versions match there should not be any problems.只要 servlet api 版本匹配就不会有任何问题。 But if your servlets are compiled against a different api version, for instance they are compiled using Servlet v4, but you try to use them in a Servlet v3 environment you will get runtime errors但是,如果您的 servlets 是针对不同的 api 版本编译的,例如它们是使用 Servlet v4 编译的,但您尝试在 Servlet v3 环境中使用它们,则会出现运行时错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM