首页>代码>通往架构师基础必备/详细剖析java web客户端和服务端交互时程序中HTTP协议的传输过程>/WebServer_v16/src/main/java/com/webserver/core/ClientHandler.java
package com.webserver.core; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.Socket; import com.webserver.http.HttpContext; import com.webserver.http.HttpRequest; import com.webserver.http.HttpResponse; /** * 用户处理客户端请求并予以响应的处理类 * @author soft01 * */ public class ClientHandler implements Runnable{ private Socket socket; public ClientHandler(Socket socket) { this.socket = socket; } public void run() { try { /* * 处理客户端请求分为三步: * 1:准备工作 * 2:处理请求 * 3:发送响应 */ //1.1:解析请求 HttpRequest request = new HttpRequest(socket); //1.2创建响应对象,发送一个标准的HTTP响应给客户端 HttpResponse response = new HttpResponse(socket); //2:处理请求 //2.1获取请求的抽象路径 String path = request.getRequestURI(); //是否为请求一个业务 //根据URL查找类名:如:/myweb/reg String className = HttpContext.getServletClass(path); /* * 如果用户的请求URL path能够找到对应的Servlet类,则利用反射执行这个Servlet * 相反如果没有对应的Servlet类,则查找磁盘URL对应的磁盘文件作为响应结果 */ if(className != null) { //类名查找到后利用反射执行对应的Servlet //1:动态加载类 Class cls = Class.forName(className); System.out.println(cls); //2:动态创建对象 Object obj = cls.newInstance(); System.out.println(obj); //3:动态查找service方法 Method method = cls.getDeclaredMethod("service", HttpRequest.class,HttpResponse.class); System.out.println(method); //4:利用反射API执行方法 method.invoke(obj, request,response); }else { //2.2去webapps目录下找到对应的资源 File file = new File("webapps"+path); //2.3判断该资源是否真实存在的 if(file.exists()) { System.out.println("资源已经找到"); //将要响应给客户端的资源设置到响应对象中 response.setEntity(file); }else { System.out.println("404!"); //设置状态代码为404 response.setStatusCode(404); //响应404页面 response.setEntity(new File("webapps/root/404.html")); } } /* * 响应 该内容给客户端 * 1:发送状态行 * 2:发送响应头 * 3:发送响应正文(实际文件的数据) */ response.flush(); } catch(EmptyRequestException e) { System.out.println("空请求..."); } catch (Exception e) { e.printStackTrace(); }finally { //最后与客户端断开链接 try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }

yhtech2015 LV8
2019年8月26日
zuidaima005 LV10
2019年6月6日
可是不知道么 LV23
2019年5月17日
qq1453363097 LV13
2019年4月24日
浪子在路上 LV12
2019年4月22日
zuidaima21533 LV1
2019年4月19日
sunliwei LV8
2019年4月19日
小牧34556 LV8
2019年4月17日
最代码官方 LV168
2019年4月12日

gougeyishi
2024年6月22日
暂无贡献等级
wan4444 LV1
2023年6月29日
qq232323
2023年5月29日
暂无贡献等级
哼哈二将哈哈哈哈啊哈
2022年12月20日
暂无贡献等级
Murmure LV2
2022年12月9日
crosa_Don LV18
2022年6月7日
gqb0123 LV1
2022年4月8日
a5366869 LV7
2021年10月31日
是pangpang呀 LV6
2021年7月10日
ericxu1116 LV24
2021年6月26日