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();
}
}
}