Java实现简易版Web容器,支持Servlet扩展

该容器基于http1.1,为了简单起见,没有实现对长连接的支持,这里只是为了了解web容器的原理。
主要承担的角色有WebServer,Response和Request类,基于TCP的Socket实现的Web容器。
实现思路:
1、构造WebServer主程,创建TcpSocket监听
2、获取到Socket的InputStream和OutputStream分别构造Request和Response
3、获取Http报文,根据请求路径,从web.xml中看是否能够匹配到servlet,如果匹配不到,就从根路径下,找有没有这个文件,如果有则通过outPutStream输出,否则输出404。

这里写图片描述

这里写图片描述

WebServer的实现

基于TCP的Socket实现。
值得注意的是,读取到配置文件之后,应该用反射来生成对象,然后调用对象的doGet或者doPost()

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 实现一个Web服务器,Http协议是基于Tcp连接的
 * 这里使用Tcp的Socket,并实现200和404
 * 实现多个客户与webserver通信
 * @author Lenovo
 *
 */

public class WebServer {
    private static boolean started = true;
    public static void main(String[] args) {
        new Thread(new Controller()).start();
    }


    private static class Server implements Runnable{
        @Override
        public void run() {
            ServerSocket server = null;
            try {
                server = new ServerSocket(8080,3,InetAddress.getByName("127.0.0.1"));
                while(!Thread.currentThread().isInterrupted()){
                    Socket s = server.accept();
                    System.out.println("有客户连接");
                    Client c = new Client(s);           
                    new Thread(c).start();
                }       

            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try{
                    if(server != null){
                        server.close();
                        System.out.println("服务器已关闭");
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
            }       
        }

    }

    private static class Client implements Runnable{
        private Socket s;
        private Response response;
        private Request request;
        public Client(Socket s){
            this.s = s;
        }
        @Override
        public void run() {
            try {
                request = new Request(s.getInputStream());
                String filename = request.parse();
                //这里应该判断filename的类型,应该先去web.xml中找看看有没有配置servlet
                //如果配置了servlet,就应该调用servlet中的dopost或者doGet方法
                //如果没有配置,就再项目下找有没有这个文件,如果有,就通过流发出去
                String servletName = XMLManager.getClassURL(filename);
                if(servletName == null){
                    response = new Response(s.getOutputStream(),filename);
                    response.response();
                }else{
                    response = new Response(s.getOutputStream());
                    response.sendHeader();
                    //反射调用方法
                    try {
                        Class clazz = Class.forName(servletName);
                        Method m = clazz.getMethod("doGet",Request.class,Response.class);
                        m.invoke(clazz.newInstance(), request,response);
                    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {

                        e.printStackTrace();
                    }           
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                //通信完成 应该关闭连接,如果是http1.1设置了保活连接,那么关闭连接的方式应该用一个线程来实现
                //为了简单起见,这里不开启keep-alive
                try{
                    s.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }

        }
    }
    /*
     * 用来控制webserver
     */
    private static class Controller implements Runnable{
        Thread t = null;
        @Override
        public void run() {
            while(true){
                Scanner scan = new Scanner(System.in);
                String command = scan.nextLine();
                if("shutdown".equals(command)){
                    t.interrupt();
                }else if("start".equals(command)){
                    Server s = new Server();
                    t = new Thread(s);
                    t.start();
                }
            }
        };
    }
}

Response

主要用来响应报文

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;


public class Response {
    private OutputStream os = null;
    private String filename = null; //request请求路径
    public Response(OutputStream os){
        this.os = os;
    }

    public Response(OutputStream os,String filename){
        this.os = os;
        this.filename = filename;
    }

    /**
     * 获取打印流
     * @return
     */
    public PrintWriter getWriter(){
        PrintWriter writer = new PrintWriter(os);
        return writer;
    }

    /**
     * 获取输出流
     * @return
     */
    public OutputStream getOutputStream(){
        return this.os;
    }

    public void sendHeader() throws IOException{
        String header = "HTTP/1.1 200 OK \r\n" +  
                "Content-Type: text/html\r\n" +  
                "\r\n";     
        os.write(header.getBytes());
        os.flush();
    }

    /**
     * 只有在响应html的时候使用
     * @throws IOException 
     */
    public void response() throws IOException{
        //获取当前根目录
        String path = System.getProperty("user.dir");
        if(path != null && filename != null){
            File file = new File(path,filename);
            if(file.exists()){
                FileInputStream ifs = new FileInputStream(file);    
                String header = "HTTP/1.1 200 OK \r\n" +  
                         "Content-Type: text/html\r\n" +  
                         "\r\n";
                //这里还应该加一个Connection字段,基于Http1.1标准,可以实现keep-alive连接
                os.write(header.getBytes());
                byte[] buffer = new byte[1024];
                int len = ifs.read(buffer,0,1024);
                while(len != -1){
                    os.write(buffer,0,len);
                    len = ifs.read(buffer, 0, 1024);
                }   
                os.flush();
                ifs.close();
            }else{
                String msg = "HTTP/1.1 404 File Not Found \r\n" +  
                         "Content-Type: text/html\r\n" +  
                         "Content-Length: 100\r\n" +  
                         "\r\n" +  
                         "<h1>404 File Not a Found!</h1>"; 
                os.write(msg.getBytes());
                os.flush();
            }
        }
    }
}

Request

import java.io.IOException;
import java.io.InputStream;


public class Request {
    private InputStream is = null;
    public Request(InputStream is){
        this.is = is;
    }

    public InputStream getInputStream(){
        return this.is;
    }

    /**
     * 解析Http报文
     * @throws IOException 
     */
    public String parse() throws IOException{
        byte[] buffer = new byte[2048];
        int i = 0;      
        i = is.read(buffer);
        String content = new String(buffer);
        return getFilename(content);
    }


    private String  getFilename(String content){
        int a,b;
        a = content.indexOf(' ');
        if(a != -1){
            b = content.indexOf('?',a+1);
            if(b == -1) b = content.indexOf(' ',a+1);
            return content.substring(a+2,b);
        }
        return null;
    }
}

读取配置类

这里使用的是Dom4J读取xml配置
如何使用dom4j
先来看看XML的内容
为了方便起见,没有使用原本的servlet的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0">
    <servlet url="/servlet" class="MyServlet"></servlet>
</web-app>
import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class XMLManager {
    public static String getClassURL(String url){
        File file = new File(XMLManager.class.getClassLoader().getResource("web.xml").getPath());
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(file);
            Element root = document.getRootElement();

            for(Iterator<Element> it = root.elementIterator();it.hasNext();){
                Element element = it.next();
                if("servlet".equals(element.getName())){
                    Attribute attrUrl = element.attribute("url");
                    Attribute attrClass = element.attribute("class");
                    if(attrUrl != null && attrUrl.getText().equals("/" + url)){
                        return attrClass.getText();
                    }
                }
            }                   
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Servlet

这里定义了Servlet接口作为Servlet的标准

import java.io.IOException;


public interface HttpServlet {
    public void doPost(Request request,Response response) throws IOException;
    public void doGet(Request request,Response response) throws IOException;
    public void init();
}

Servlet的实现

import java.io.IOException;
import java.io.PrintWriter;

public class MyServlet implements HttpServlet{

    @Override
    public void doPost(Request request, Response response) throws IOException {
        PrintWriter out = response.getWriter();
        out.print("<h1>hello word</h1>");
        out.flush();
        out.close();
    }

    @Override
    public void doGet(Request request, Response response) throws IOException {
        doPost(request, response);
    }

    @Override
    public void init() {

    }

}

测试

启动WebServer之后,输入start启动服务
浏览器输入 http://localhost:8080/index.html (这个html需要自己写)
或者输入 http://localhost:8080/servlet

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值