maven工程目录和类加载器ClassLoader的记录
URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.", "/"));
上面的结果返回为null
严重: StandardWrapper.Throwable
java.lang.NullPointerException
at com.kaikai.servlet.MyDispatcherServlet.doScanner(MyDispatcherServlet.java:153)
at com.kaikai.servlet.MyDispatcherServlet.init(MyDispatcherServlet.java:35)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
at java.util.concurrent.FutureTask.run(FutureTask.java)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
getResource方法要注意类路径
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
// URL url = myTest.getClass().getClassLoader().getResource("/");
URL url = myTest.getClass().getClassLoader().getResource("");
System.out.println(url);
}
}
测试后发现方法参数为""
,返回的url是类路径的。
maven工程编译后的class文件目录结构的类路径,不需要以/
开头。
URL url = this.getClass().getClassLoader().getResource(packageName.replaceAll("\\.", "/"));
就正常了