手寫嵌入式Tomcat(帶詳細註解)

導讀

本文分爲兩部分 1. 實現思路分析部分 2. 實現代碼部分html

運行代碼需導入tomcat7maven插件,代碼基於TomcatAPI實現web

一. 實現思路分析

使用Tomcat的API實現, 步驟以下apache

  1. 新建一個Tomcat對象
  2. 設置Tomccat的端口號
  3. 設置Context目錄
  4. 添加Servlet容器
  5. 調用Tomcat對象start()
  6. 強制Tomcat等待

二.實現代碼

MyTomcatServer 代碼以下windows

public class MyTomcatServer {

    public static void main(String[] args) throws Exception {
        // 把目錄的絕對路徑獲取到
        String classpath = System.getProperty("user.dir");
        System.out.println(classpath);
        Tomcat tomcat = new Tomcat();
        // 設置Tomcat的端口
        Connector connector = tomcat.getConnector();
        connector.setPort(9091);
        // 設置Host
        Host host = tomcat.getHost();
        host.setName("localhost");
        host.setAppBase("webapps");
        // 加載class
        Context context = tomcat.addContext(host, "/",classpath);
        if (context instanceof StandardContext){
            StandardContext standardContext = (StandardContext) context;
            // 加載本身的web.xml配置文件
            standardContext.setDefaultContextXml("D:/workAPP/apache-tomcat-8.5.39-windows-x64/apache-tomcat-8.5.39/conf/web.xml");
            // 設置Servlet
            Wrapper wrapper = tomcat.addServlet("/", "MyServlet", new MyServlet());
            // 設置訪問路徑
            wrapper.addMapping("/lilei");
        }

        // Tomcat啓動
        tomcat.start();
        // 強制Tomcat server等待, 避免main線程執行結束後關閉
        tomcat.getServer().await();
    }
}
複製代碼

Servlet代碼以下:tomcat

public class MyServlet implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("ok!!");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("<h1>ok!!! <b>李磊加油!!</h1>");
        writer.close();
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
複製代碼

三. 結束

感謝讀者朋友的閱讀! 前路願與你們一同探索!!!bash

相關文章
相關標籤/搜索