palfish
palfish
采纳率100%
2017-06-09 05:46

URLClassLoader加载本地类文件为什么总是报ClassNotFound?求大神解惑

3
已采纳

public class ServletProcessor1 {

public void process(Request request, Response response) {
        String uri            = request.getUri();
        String servletName    = uri.substring(uri.lastIndexOf("/") + 1);
        URLClassLoader loader = null;

        try {
            // create a URLClassLoader
            URLStreamHandler streamHandler = null;

            URL[] urls        = new URL[1];
            File classPath    = new File(HttpServer1.WEB_ROOT);
            String repository = (new URL("file", null, 
                classPath.getCanonicalPath() + File.separator)).toString() ;
            urls[0]           = new URL(null, repository, streamHandler);
            loader            = new URLClassLoader(urls);
            System.out.println(loader.findResource(servletName));
        }
        catch (IOException e) {
            System.out.println(e.toString() );
        }

        Class<?> myClass = null;

        try {
            myClass = loader.loadClass(servletName);
        }
        catch (ClassNotFoundException e) {
            System.out.println(e.toString());
        }
        Servlet servlet = null;
        try {
            servlet = (Servlet) myClass.newInstance();
            servlet.service((ServletRequest) request, (ServletResponse) response);
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
        catch (Throwable e) {
            System.out.println(e.toString());
        }
}

}

java.lang.ClassNotFoundException: PrimitiveServlet
java.lang.NullPointerException

Exception in thread "main" java.lang.NullPointerException
at ex02.pyrmont.HttpServer1.await(HttpServer1.java:50)
at ex02.pyrmont.HttpServer1.main(HttpServer1.java:22)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • lihongbiao0610 lihongbiao0610 4年前

    servletName应该是包名+类名。如com.test.PrimitiveServlet

    点赞 评论 复制链接分享
  • ljheee ljheee 4年前

    总是报ClassNotFound,是不是导包 导错了

    点赞 评论 复制链接分享
  • qq_35498454 xhl_2017 4年前

    你用的是什么框架?这个是配置问题

    点赞 评论 复制链接分享