栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JSD-2204-WebServer(项目)-Day12

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JSD-2204-WebServer(项目)-Day12

1.V6(版本)
测试目标:将index.html页面发送给浏览器
从而了解HTTP的响应格式
1:用File对象表示resources下的static目录中myweb目录中的index.html
2:通过socket获取输出流
3:通过输出流将一个标准的HTTP响应内容发送给浏览器,其中就包含了index页面

在maven项目中,java的源码文件和其他文件是要分开存放的。
所有java源码文件放在:src/main/java中
而所有的其他资源文件放在:src/main/resources中
但是当编译后,IDEA会将java目录和resources目录合并保存在
target/classes中。
所以我们可以理解为java目录和resources目录就是同一个目录
1.1项目目录

1.2Java代码 1.2.1WebServerApplication(启动类)

没有改动和之前V5版本一致 

1.2.2ClientHandle
package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            //2处理请求
            String path = request.getUri();

            //3发送响应
            
            //由于编译后所有内容都合并放在了target/classes下,因此从该目录开始寻找资源
            File rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );
            //从根目录开始定位下面保存所有静态资源的目录"static"
            
            File staticDir = new File(rootDir,"static");

            //定位static目录下myweb目录中的index.html
            
            File file = new File(staticDir,path);
            System.out.println("资源是否存在:"+file.exists());

            

            //3.1发送状态行
            println("HTTP/1.1 200 OK");
            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: " + file.length());
            //单独发送回车+换行表示响应头部分发送完毕了
            println("");
            //3.3将文件的所有字节作为正文内容发送给浏览器
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] buf = new byte[1024*10];//10kb
            int len;//记录每次实际读取到的字节数
            while((len = fis.read(buf)) != -1) {
                out.write(buf,0,len);
            }



        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                //按照HTTP协议要求,一次交互后要断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);//发送状态行内容
        out.write(13);//发送回车符
        out.write(10);//发送换行符
    }



}
1.2.3HttpServletRequest
package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;


public class HttpServletRequest {
    private Socket socket;

    //请求行的相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本

    //用一个Map保存所有的消息头,其中key:消息头名字,value:消息头的值
    private Map headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }

    //解析请求行
    private void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);
        //将请求行按照空格拆分为三部分,并赋值给三个变量
        String[] data = line.split("\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        //测试路径:http://localhost:8088/myweb/index.html
        System.out.println("method:"+method);//method:GET
        System.out.println("uri:"+uri);//uri:/myweb/index.html
        System.out.println("protocol:"+protocol);//protocol:HTTP/1.1
    }
    //解析消息头
    private void parseHeaders() throws IOException {
        while(true) {
            String line = readLine();
            if(line.isEmpty()){//读取单独读取了CRLF则停止循环
                break;
            }
            System.out.println(line);
            String[] data = line.split(":\s");
            headers.put(data[0].toLowerCase(),data[1]);

        }
        System.out.println(headers);
    }
    //解析消息正文
    private void parseContent(){}

    
    private String readLine() throws IOException {
        
        InputStream in = socket.getInputStream();
        int d ;
        char cur='a',pre='a';//cur表示本次读取的字符,pre表示上次读取的字符
        StringBuilder builder = new StringBuilder();
        while((d = in.read()) != -1){
            cur = (char)d;//本次读取到的字符
            if(pre==13&&cur==10){//是否连续读取了回车+换行
                break;
            }
            builder.append(cur);
            pre = cur;//在进行下一轮读取前,要将本次读取的字符记作"上次读取的字符"
        }
        return builder.toString().trim();//获取拼接好的一行字符串内容
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name) {
        return headers.get(name);
    }
}
1.3HTML代码 1.3.1index.html



    
    我的首页



    
百度
淘宝
第一列 第二列 第三列
第一列 第二列 第三列 第四列
第二列 第三列 第四列

 页面展示效果:

1.3.2classTable.html(小练习)



    
    课程表


  
课程表
  星期一 星期二 星期三 星期四 星期五
上午 语文 数学 英语 体育 生物
生物 数学 英语 语文 体育
生物 数学 英语 语文 体育
生物 数学 英语 语文 体育
午休,bilibili一下
下午 语文 数学 英语 体育 生物
生物 数学 英语 语文 体育
生物 数学 英语 语文 体育
生物 数学 英语 语文 体育

页面展示效果:

  

2.V7(版本)
如果file定位的是一个真实存在的文件则正常响应下面内容
HTTP/1.1 200 OK(CRLF)
Content-Type: text/html(CRLF)
Content-Length: 2546(CRLF)(CRLF)
1011101010101010101......
否则
HTTP/1.1 404 NotFound(CRLF)
Content-Type: text/html(CRLF)
Content-Length: xxxx(CRLF)(CRLF)
1011101010101010101......(404.html页面内容)
2.1项目目录

2.2Java代码 2.2.1WebServerApplication(启动类)

没有改动和之前V6版本一致 

2.2.2ClientHandle
package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            //2处理请求
            String path = request.getUri();

            //3发送响应
            
            //由于编译后所有内容都合并放在了target/classes下,因此从该目录开始寻找资源
            File rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );
            //从根目录开始定位下面保存所有静态资源的目录"static"
            
            File staticDir = new File(rootDir,"static");

            //定位static目录下myweb目录中的index.html
            
            File file = new File(staticDir,path);
            System.out.println("资源是否存在:"+file.exists());
            
            String line;
            if(file.isFile()){
                line = "HTTP/1.1 200 OK";
            }else{
                line = "HTTP/1.1 404 NotFound";
                file = new File(staticDir,"/root/404.html");
            }


            //3.1发送状态行
            println(line);
            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-Length: " + file.length());
            //单独发送回车+换行表示响应头部分发送完毕了
            println("");
            //3.3将文件的所有字节作为正文内容发送给浏览器
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] buf = new byte[1024*10];//10kb
            int len;//记录每次实际读取到的字节数
            while((len = fis.read(buf)) != -1) {
                out.write(buf,0,len);
            }



        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                //按照HTTP协议要求,一次交互后要断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);//发送状态行内容
        out.write(13);//发送回车符
        out.write(10);//发送换行符
    }



}
2.2.3HttpServletRequest
package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;


public class HttpServletRequest {
    private Socket socket;

    //请求行的相关信息
    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本

    //用一个Map保存所有的消息头,其中key:消息头名字,value:消息头的值
    private Map headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }

    //解析请求行
    private void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);
        //将请求行按照空格拆分为三部分,并赋值给三个变量
        String[] data = line.split("\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        //测试路径:http://localhost:8088/myweb/index.html
        System.out.println("method:"+method);//method:GET
        System.out.println("uri:"+uri);//uri:/myweb/index.html
        System.out.println("protocol:"+protocol);//protocol:HTTP/1.1
    }
    //解析消息头
    private void parseHeaders() throws IOException {
        while(true) {
            String line = readLine();
            if(line.isEmpty()){//读取单独读取了CRLF则停止循环
                break;
            }
            System.out.println(line);
            String[] data = line.split(":\s");
            headers.put(data[0].toLowerCase(),data[1]);

        }
        System.out.println(headers);
    }
    //解析消息正文
    private void parseContent(){}

    
    private String readLine() throws IOException {
        
        InputStream in = socket.getInputStream();
        int d ;
        char cur='a',pre='a';//cur表示本次读取的字符,pre表示上次读取的字符
        StringBuilder builder = new StringBuilder();
        while((d = in.read()) != -1){
            cur = (char)d;//本次读取到的字符
            if(pre==13&&cur==10){//是否连续读取了回车+换行
                break;
            }
            builder.append(cur);
            pre = cur;//在进行下一轮读取前,要将本次读取的字符记作"上次读取的字符"
        }
        return builder.toString().trim();//获取拼接好的一行字符串内容
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name) {
        return headers.get(name);
    }
}

没有改动和之前V6版本一致 

2.3HTML代码

其他没有改动

2.3.1 404.html



    
    404


  
404,资源不存在!

页面展示效果:

 

3.V8(版本)
完成404的响应
上一个版本中我们已经实现了根据浏览器中用户在地址栏上输入的URL中的抽象路径去
static目录下寻找对应资源进行响应的工作。

但是会存在路径输入有误,导致定位不对(要么定位的是一个目录,要么该文件不存在)
此时再发送响应的响应正文时使用文件输入流读取就会出现异常提示该资源不存在。

这是一个典型的404情况,因此我们在ClientHandler处理请求的环节,在实例化File
对象根据抽象路径定位webapps下的资源后,要添加一个分支,若该资源存在则将其响应
回去,如果不存在则要响应404状态代码和404页面提示用户。

实现:
1:在static下新建一个子目录root
  该目录用于保存当前服务端所有网络应用共用的资源,比如404页面,因为无论请求哪个
  网络应用中的资源都可能发生不存在的情况。
2:在root目录下新建页面:404.html
  该页面居中显示一行字即可:404,资源不存在!
3:在ClientHandler处理请求的环节,当实例化File对象后添加一个分支,如果该File
  对象存在且表示的是一个文件则将其响应给浏览器
  否则发送的响应做如下变化:
  1:状态行中的状态代码改为404,状态描述改为NotFound
  2:响应头Content-Length发送的是404页面的长度
  3:响应正文为404页面内容
完成后,在浏览器地址栏输入一个不存在的资源地址,检查服务端是否正确响应404页面

http://localhost:8088/
http://localhost:8088/myweb/
http://localhost:8088/myweb/123.html
3.1项目目录

3.2Java代码 3.2.1WebServerApplication(启动类)

没有改动和之前V7版本一致 

3.2.2ClientHandle
package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            //2处理请求
            String path = request.getUri();
            File rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );
            File staticDir = new File(rootDir,"static");
            File file = new File(staticDir,path);
            System.out.println("资源是否存在:"+file.exists());
            if(file.isFile()){
                //将请求的实际文件设置到response的正文上等待响应
                response.setContentFile(file);
            }else{
                file = new File(staticDir,"/root/404.html");
                //将404内容设置到response上等待响应
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                response.setContentFile(file);
            }

            //3发送响应
            response.response();



        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                //按照HTTP协议要求,一次交互后要断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }





}
3.2.3HttpServletRequest

没有改动和之前V7版本一致 

3.2.4HttpServletResponse
package com.webserver.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


public class HttpServletResponse {
    private Socket socket;

    //状态行相关信息
    private int statusCode = 200;//状态代码,默认为200
    private String statusReason = "OK";//状态描述,默认为OK

    //响应正文相关信息
    private File contentFile;//响应正文对应的实体文件




    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    
    public void response() throws IOException {
        //3.1发送状态行
        sendStatusLine();
        //3.2发送响应头
        sendHeaders();
        //3.3将文件的所有字节作为正文内容发送给浏览器
        sendContent();
    }
    //发送状态行
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1" + " " + statusCode + " " + statusReason);
    }
    //发送响应头
    private void sendHeaders() throws IOException {
        println("Content-Type: text/html");
        println("Content-Length: " + contentFile.length());
        //单独发送回车+换行表示响应头部分发送完毕了
        println("");
    }
    //发送响应正文
    private void sendContent() throws IOException {
        //try()意味着编译后有finally用于遍历流。所以这不违背try不能单独定义的原则
        try(
            FileInputStream fis = new FileInputStream(contentFile);
        ) {
            OutputStream out = socket.getOutputStream();
            byte[] buf = new byte[1024 * 10];//10kb
            int len;//记录每次实际读取到的字节数
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
        }
    }




    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);//发送状态行内容
        out.write(13);//发送回车符
        out.write(10);//发送换行符
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
3.3HTML代码

其他没有改动

3.4代码运行流程图 

4.V9(版本)
重构代码
将ClientHandler中处理请求的操作拆分出去

实现:
1:在com.webserver.core包下新建类:DispatcherServlet
  并定义service方法,用来处理请求
2:将ClientHandler处理请求的操作移动到service方法中去
3:ClientHandler通过调用DispatcherServlet的service完成处理请求环节.
4.1项目目录

4.2Java代码 4.2.1WebServerApplication(启动类)

没有改动和之前V8版本一致 

4.2.2ClientHandle
package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);

            //2处理请求
            DispatcherServlet servlet = new DispatcherServlet();
            servlet.service(request,response);

            //3发送响应
            response.response();



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //按照HTTP协议要求,一次交互后要断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }





}
4.2.3HttpServletRequest

没有改动和之前V8版本一致 

4.2.4HttpServletResponse

没有改动和之前V8版本一致 

4.2.5DispatcherServlet
package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;


public class DispatcherServlet {
    private static File rootDir;
    private static File staticDir;

    static{
        try {
            rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();

        File file = new File(staticDir,path);
        System.out.println("资源是否存在:"+file.exists());
        if(file.isFile()){
            //将请求的实际文件设置到response的正文上等待响应
            response.setContentFile(file);
        }else{
            file = new File(staticDir,"/root/404.html");
            //将404内容设置到response上等待响应
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            response.setContentFile(file);
        }
    }
}
3.3HTML代码

其他没有改动

3.4代码运行流程图

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979515.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号