java實踐:tomcat_簡化版_服務呼叫(不含網路和協議)

weixin_33890499發表於2017-12-07
9106490-6ec8a22d494de733.png
image.png

一、請求和響應

package com.guoyasoft.tomcat;
public class Request {

}
package com.guoyasoft.tomcat;

public class Response {

}

二、定義父類

package com.guoyasoft.tomcat;

public class HTTPServlet {
    public void doGet(Request req,Response resp){
        System.out.println("不支援 get 方式");
    }
    public void doPost(Request req,Response resp){
        System.out.println("不支援 post 方式");
    }
}

三、tomcat服務

properties配置檔案

/NewWeb/src/main/java/com/guoyasoft/web.properties
package com.guoyasoft.tomcat;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

public class Tomcat {
    public void http(String url) throws Exception{
        //第一步:解析配置檔案
        InputStream is =new FileInputStream("src/main/java/com/guoyasoft/web.properties");
        Properties prop=new Properties();
        prop.load(is);
        //第二步:根據請求找到對應的java類
        String className=prop.getProperty(url);
        System.out.println(className);
        //第三步:反射,拿到型別物件
        Class c=Class.forName(className);
        
        //第四步:new一個例項,向上轉型成HTTPServlet
        HTTPServlet obj=(HTTPServlet) c.newInstance();
        
        //第五步:找到方法
        Method m=c.getMethod("doGet", Request.class,Response.class);
        
        //第六步:準備呼叫引數
        Request request=new Request();
        Response response=new Response();
        
        //第七步:呼叫該例項的方法
        Object[] objs=new Object[2];
        objs[0]=request;
        objs[1]=response;
        m.invoke(obj, objs);

//      m.invoke(obj, new Object[]{request,response});
    }
}

四、編寫幾個介面

package com.guoyasoft.servelet;

import com.guoyasoft.tomcat.HTTPServlet;
import com.guoyasoft.tomcat.Request;
import com.guoyasoft.tomcat.Response;

public class Login extends HTTPServlet{

    @Override
    public void doGet(Request request, Response response) {
        System.out.println("login 呼叫成功");
    }

}

釋出到tomcat配置檔案:

login=com.guoyasoft.servelet.Login
package com.guoyasoft.servelet;

import com.guoyasoft.tomcat.HTTPServlet;
import com.guoyasoft.tomcat.Request;
import com.guoyasoft.tomcat.Response;

public class Logout extends HTTPServlet{

    @Override
    public void doGet(Request request, Response response) {
        System.out.println("logout 成功");
    }

}

釋出到tomcat配置檔案:

logout=com.guoyasoft.servelet.Logout

五、寫客戶端程式碼呼叫

package com.guoyasoft.client;
import com.guoyasoft.tomcat.Tomcat;
public class Test {
    public static void main(String[] args) {
        Tomcat t=new Tomcat();
        try {
            t.http("searchStudent");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

相關文章