对Servlet容器的补充和一个问题的请教

【0】README

0.1)本文是对 一个servlet容器  的补充;

0.2)发这个博文的最终目的是为了请教各位前辈,帮我解决一个问题,问题描述在文末, 谢谢;

【1】Servlet容器

1.1)通过一个简单的servlet容器这篇博文,我们看到:其中的核心代码是 类加载器, 然而,在我follow 其代码,分别在命令行 和 Eclipse 执行时,得到了不同的执行结果; 参见我的提问 对于URLClassLoader,Eclipse执行正确,而命令行执行抛出异常 这个问题描述;

1.2)抛出异常的原因: 显然是 类加载器没有找到要加载类所在的dir, 然而,正如你所见,我在 URLClassLoader的源代码中已经 指定了加载路径;

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. try {  
  2.       // create a URLClassLoader, 创建类载入器(类加载器是干货代码 )  
  3.       URL[] urls = new URL[1];  
  4.       URLStreamHandler streamHandler = null;  
  5.       File classPath = new File(Constants.WEB_ROOT);  
  6.       // the forming of repository is taken from the createClassLoader method in  
  7.       // org.apache.catalina.startup.ClassLoaderFactory  
  8.       String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;  
  9.       // file:E:ench-clustercloud-data-preprocessHowTomcatWorkswebroot  
  10.       // the code for forming the URL is taken from the addRepository method in  
  11.       // org.apache.catalina.loader.StandardClassLoader class.  
  12.       urls[0] = new URL(null, repository, streamHandler);  
  13.       // urls[0] = file:E:/bench-cluster/cloud-data-preprocess/HowTomcatWorks/webroot/  
  14.       loader = new URLClassLoader(urls);  
  15.     }  

1.3)解决方法:正如你在 “一个简单的servlet容器” 这篇博文中所见,我需要再 命令行运行该程序时,手动添加 类加载路径到 classpath, 这样才能执行成功,否则失败。

 

Attention)我纳闷的地方在于:明明在上述代码中,我已经在 URLClassLoader的类构造器中指明了 类加载路径,为什么我还要在命令行手动设置类加载路径到 classpath,那岂不是我在URLClassLoader 中指明的 类加载路径是 invalid ? 也就是上述我在技术问题中所提出的问题,但是这个问题(对于URLClassLoader,Eclipse执行正确,而命令行执行抛出异常 )一直没有人来解答。

原文地址:https://www.cnblogs.com/pacoson/p/5363842.html