URLClassloader 載入本地方法

雪過梅香發表於2020-10-14
package cn.how2j.diytomcat.servlet;

import cn.how2j.diytomcat.Request;
import cn.how2j.diytomcat.Response;
import cn.how2j.http.HttpServer;
import org.apache.tomcat.util.scan.Constants;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/**
 * @author WangYifei
 * @desc Servlet 處理類
 */
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
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            File file = new File(System.getProperty("user.dir") + File.separator + "webroot" + File.separator +  "wyf-diytomcat.jar");
            urls[0] = file.toURI().toURL();
            System.out.println(urls[0]);
            loader = new URLClassLoader(urls);
        } catch (IOException e) {
            System.out.println(e.toString());
        }

        Class myClass = null;

        try {
            System.out.println(servletName);
            myClass = loader.loadClass("cn.how2j.diytomcat.servlet.PrimitiveServlet");
        } catch (ClassNotFoundException e) {
            System.out.println(e.toString());
        }

        Servlet servlet = null;

        try {
            servlet = (Servlet) myClass.newInstance();
            servlet.service(request, response);
        } catch (InstantiationException e) {
            System.out.println(e.toString());
        } catch (IllegalAccessException e) {
            System.out.println(e.toString());
        } catch (ServletException e) {
            System.out.println(e.toString());
        } catch (IOException e) {
            System.out.println(e.toString());
        }


    }
}

從《深入剖析tomcat》中看到使用URLClassloader載入,一步一步跟著做,可能由於部分沒有寫出來,自己百度瞭解到URLClassloader載入的是jar包,通過loadClass 去使用jar,對jar中的某個類進行例項化,為了下一步手動將本專案打包成為jar之後設定固定值進行測試,為了學習下一步,雖然還有一部分問題並且與書中程式碼不一致,現在不知道怎麼實現,但是基本概念已經有了,可以進行下一步的學習了。

相關文章