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

JSD-2204-WebServer(项目)-Day13

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

JSD-2204-WebServer(项目)-Day13

1.V10(版本)
在index页面上显示一张图片

实现:
1:准备一张图片,取名为logo.png
2:在index.html页面上使用标签将其显示出来
3:启动服务端,使用浏览器请求该页面查看图片的显示情况.

测试发现图片无法加载.
原因:
当页面上需要加载其他资源(图片,样式文件,脚本文件等)时,浏览器会自动发起请求去下载
这些资源.因此当我们的页面上有其他资源时,呈现一个页面一问一答就不够了,需要多次的
请求响应来完成.

解决:
将WebServerApplication的start方法中的代码加上死循环,重复接收多次客户端的
连接即可.
1.1项目目录

 

1.2Java页面 1.2.1ClientHandler
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();
            }
        }

    }





}

1.2.2DispatcherServlet
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);
        }
    }
}

1.2.3WebServerApplication
package com.webserver.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class WebServerApplication {
    private ServerSocket serverSocket;

    
    public WebServerApplication(){
        try {
            System.out.println("正在启动服务端...");
            
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    public void start(){
        try {
            while(true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了!");
                //启动一个线程处理该客户端交互
                ClientHandler clientHandler = new ClientHandler(socket);
                Thread thread = new Thread(clientHandler);
                thread.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        WebServerApplication webServerApplication = new WebServerApplication();
        webServerApplication.start();
    }
}

1.2.4HttpServletRequest
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.2.5HttpServletResponse
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;
    }
}
1.3HTML页面

没有改动

2.V11(版本)
导入学子商城webapp资源后访问其首页,发现页面无法正常显示.
浏览器F12跟踪请求和响应的交互发现两个问题:
1:我们仅发送了两个响应头(Content-Length和Content-Type).
  虽然目前仅需要这两个头,但是服务端实际可以根据处理情况设置需要发送其他响应头
2:Content-Type的值是固定的"text/html",这导致浏览器请求到该资源后无法正确
  理解该资源因此没有发挥出实际作用.

分两个版本解决这两个问题
此版本解决响应头可根据设置进行发送.

实现:
1:在HttpServletResponse中添加一个Map类型的属性用于保存所有要发送的响应头
  Map headers

2:修改发送响应头的方法sendHeaders中的逻辑,将固定发送两个头的操作改为遍历
  headers这个Map,将所有要发送的响应头逐个发送

3:只需要在发送前根据处理情况向headers中put要发送的响应头即可.这个工作需要
  3.1:在响应对象中添加一个方法:addHeader,将要发送的响应头存入headers中
  3.2:在DispatcherServlet处理请求环节调用addHeader存放要发送的响应头即可


http://localhost:8088/TeduStore/index.html
2.1项目目录

 

2.2Java页面 2.2.1ClientHandler

跟V10版本一样没有改动

2.2.2DispatcherServlet
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);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");

        }else{
            file = new File(staticDir,"/root/404.html");
            //将404内容设置到response上等待响应
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            response.setContentFile(file);
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",file.length()+"");
        }
    }
}
2.2.3WebServerApplication

跟V10版本一样没有改动

2.2.4HttpServletRequest

跟V10版本一样没有改动

2.2.5HttpServletResponse
package com.webserver.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class HttpServletResponse {
    private Socket socket;

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

    //响应头相关信息
    //key:响应头名字   value:响应头的值
    private Map headers = new HashMap<>();


    //响应正文相关信息
    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 {
        
        //遍历headers将所有的响应头发送给浏览器
        Set> entrySet = headers.entrySet();
        for(Entry e : entrySet){
            String key = e.getKey();
            String value = e.getValue();
            //println("Content-Type: text/html");
            println(key + ": " + value);
        }

        //单独发送回车+换行表示响应头部分发送完毕了
        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;
    }

    
    public void addHeader(String name,String value){
        headers.put(name,value);
    }
}
2.3HTML页面

下载了一个学子商城:

去doc.canglaoshi.org上面下载

2.4代码流程图

 

3.V12(版本)
实现HttpServletResponse响应正确的MIME类型,即:Content-Type的值
这里我们使用java.nio.file.Files这个类来完成这个功能。

这样一来,服务端就可以正确响应浏览器请求的任何资源了,使得浏览器可以正确显示内容

实现:
1:将原DispatcherServlet中设置响应头Content-Type和Content-Length的
  工作移动到HttpServletResponse的设置响应正文方法setContentFile中.
  原因:一个响应中只要包含正文就应当包含说明正文信息的两个头Content-Type和
  Content-Length.因此我们完全可以在设置正文的时候自动设置这两个头.
  这样做的好处是将来设置完正文(调用setContentFile)后无需再单独设置这两个头了.
2:使用Files的静态方法probeContentType按照正文文件分析MIME类型并设置到
  响应头Content-Type上
3.1项目目录

 

3.2Java页面 3.2.1ClientHandler

跟V11版本一样没有改动

3.2.2DispatcherServlet
package com.webserver.core;

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

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;


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.2.3WebServerApplication

跟V11版本一样没有改动

3.2.4HttpServletRequest

跟V11版本一样没有改动

3.2.5HttpServletResponse
package com.webserver.http;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class HttpServletResponse {
    private Socket socket;

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

    //响应头相关信息
    //key:响应头名字   value:响应头的值
    private Map headers = new HashMap<>();


    //响应正文相关信息
    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 {
        
        //遍历headers将所有的响应头发送给浏览器
        Set> entrySet = headers.entrySet();
        for(Entry e : entrySet){
            String key = e.getKey();
            String value = e.getValue();
            //println("Content-Type: text/html");
            println(key + ": " + value);
        }

        //单独发送回车+换行表示响应头部分发送完毕了
        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;
         
        try {
            //该方法会自动分析文件对应的Content-Type值,若无法识别会返回null
            //http://localhost:8088/TeduStore/index.html
                
            String type = Files.probeContentType(contentFile.toPath());
            if(type!=null) {
                addHeader("Content-Type", type);
            }
        } catch (IOException e) {
        }
        addHeader("Content-Length",contentFile.length()+"");


    }

    
    public void addHeader(String name,String value){
        headers.put(name,value);
    }
}
3.3HTML页面

下载了一个学子商城:

去doc.canglaoshi.org上面下载

4.V13(版本)
uri有两种情况:
1:不含有参数的
  例如: /myweb/index.html
  直接将uri的值赋值给requestURI即可.

2:含有参数的
  例如:/myweb/reg?username=fancq&password=123456&nickname=chuanqi&age=22
  将uri中"?"左侧的请求部分赋值给requestURI
  将uri中"?"右侧的参数部分赋值给queryString
  将参数部分首先按照"&"拆分出每一组参数,再将每一组参数按照"="拆分为参数名与参数值
  并将参数名作为key,参数值作为value存入到parameters中。
3:创建一个reg.html文件实现注册功能
4.1项目目录

4.2Java页面 4.2.1HttpServletRequest
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;//协议版本

    private String requestURI;//uri中的请求部分,"?"左侧的内容
    private String queryString;//uri中的参数部分,"?"右侧的内容
    private Map parameters = new HashMap<>();//每一组参数 key:参数名 value:参数值


    //用一个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];
        parseURI();//进一步解析uri
        //测试路径: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
    }
    //进一步解析URI
    private void parseURI(){
        

        String[] split = uri.split("\?");
        if (split.length>1){
            requestURI = split[0];
            queryString = split[1];
            String[] split1 = split[1].split("&");
            for (int i = 0; i < split1.length; i++) {
                String[] split2 = split1[i].split("=");
                parameters.put(split2[0],split2[1]);
            }
        }else{
            requestURI = uri;
        }
        System.out.println("requestURI"+requestURI);
        System.out.println("queryString"+queryString);
        System.out.println("parameters"+parameters);
    }

    //解析消息头
    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);
    }
}
4.3HTML页面 4.3.1reg.html(新增)
 



    
    用户注册


    
用户注册
用户名
密码
昵称
年龄

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

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

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