回顾昨天学习的地方,浏览器解析资源发送请求到服务器。服务器读取消息,解析,找人做事,响应回去。

    读取消息:包装三次得到高级流读取一行信息

    1. private void receiveRequest(){
    2. try {
    3. //流的转化
    4. InputStream is=socket.getInputStream();
    5. InputStreamReader isr=new InputStreamReader(is);
    6. BufferedReader reader=new BufferedReader(isr);
    7. //读取消息
    8. String contentAndParams=reader.readLine();
    9. this.parseContentAndParams(contentAndParams);
    10. } catch (IOException e) {
    11. e.printStackTrace();
    12. }
    13. }

    解析:解析就是为了得到浏览器发送过来的请求资源名和参数

    1. //解析
    2. private void parseContentAndParams(String contentAndParams){
    3. //创建两个变量 存储请求的资源名 携带的参数
    4. String content=null;
    5. HashMap<String,String> paramsMap=null;
    6. // content?key=value&key=value
    7. //找寻问号所载位置
    8. int questionMarkIndex=contentAndParams.indexOf("?");
    9. //判断是否携带了参数
    10. if(questionMarkIndex!=-1){
    11. content=contentAndParams.substring(0,questionMarkIndex);
    12. paramsMap=new HashMap<>();
    13. //处理问号后面的参数 拆分到map集合
    14. String params=contentAndParams.substring(questionMarkIndex+1);
    15. String []keyAndValues=params.split("?");
    16. for(String keyAndValue:keyAndValues){
    17. String []kv=keyAndValue.split("&");
    18. paramsMap.put(kv[0],kv[1]);
    19. }
    20. }else{
    21. //没有携带参数 请求发送过来的是完整的资源名
    22. content=contentAndParams;
    23. }
    24. HttpServletRequest request=new HttpServletRequest(content,paramsMap);
    25. HttpServletResponse response=new HttpServletResponse();
    26. this.findController(request,response);
    27. }

    找人做事:从请求request的对象中,获取对象的请求名字,通过加载配置文件,得到真实的类名字,利用反射得到类,得到对象方法。调用控制层那方法。

    1. private void findController(HttpServletRequest request,HttpServletResponse response){
    2. try {
    3. //获取对象中请求的名字
    4. String content = request.getContent();
    5. //参考配置文件
    6. Properties pro = new Properties();
    7. pro.load(new FileReader("src//web.properties"));
    8. String realControllerName=pro.getProperty(content);
    9. //反射获取类
    10. Class clazz=Class.forName(realControllerName);
    11. Object obj=clazz.newInstance();
    12. //反射找寻类中的方法
    13. Method method=clazz.getMethod("test",HttpServletRequest.class,HttpServletResponse.class);
    14. method.invoke(obj,request,response);
    15. } catch (Exception e) {
    16. e.printStackTrace();
    17. }
    18. }