回顾昨天学习的地方,浏览器解析资源发送请求到服务器。服务器读取消息,解析,找人做事,响应回去。
读取消息:包装三次得到高级流读取一行信息
private void receiveRequest(){try {//流的转化InputStream is=socket.getInputStream();InputStreamReader isr=new InputStreamReader(is);BufferedReader reader=new BufferedReader(isr);//读取消息String contentAndParams=reader.readLine();this.parseContentAndParams(contentAndParams);} catch (IOException e) {e.printStackTrace();}}
解析:解析就是为了得到浏览器发送过来的请求资源名和参数
//解析private void parseContentAndParams(String contentAndParams){//创建两个变量 存储请求的资源名 携带的参数String content=null;HashMap<String,String> paramsMap=null;// content?key=value&key=value//找寻问号所载位置int questionMarkIndex=contentAndParams.indexOf("?");//判断是否携带了参数if(questionMarkIndex!=-1){content=contentAndParams.substring(0,questionMarkIndex);paramsMap=new HashMap<>();//处理问号后面的参数 拆分到map集合String params=contentAndParams.substring(questionMarkIndex+1);String []keyAndValues=params.split("?");for(String keyAndValue:keyAndValues){String []kv=keyAndValue.split("&");paramsMap.put(kv[0],kv[1]);}}else{//没有携带参数 请求发送过来的是完整的资源名content=contentAndParams;}HttpServletRequest request=new HttpServletRequest(content,paramsMap);HttpServletResponse response=new HttpServletResponse();this.findController(request,response);}
找人做事:从请求request的对象中,获取对象的请求名字,通过加载配置文件,得到真实的类名字,利用反射得到类,得到对象方法。调用控制层那方法。
private void findController(HttpServletRequest request,HttpServletResponse response){try {//获取对象中请求的名字String content = request.getContent();//参考配置文件Properties pro = new Properties();pro.load(new FileReader("src//web.properties"));String realControllerName=pro.getProperty(content);//反射获取类Class clazz=Class.forName(realControllerName);Object obj=clazz.newInstance();//反射找寻类中的方法Method method=clazz.getMethod("test",HttpServletRequest.class,HttpServletResponse.class);method.invoke(obj,request,response);} catch (Exception e) {e.printStackTrace();}}
