Java Web框架 内嵌 embed Tomcat

Java Web框架 内嵌 embed Tomcat

1、下载apache-tomcat-8.5.37-embed.zip。
https://tomcat.apache.org/download-80.cgi
2、解压缩,把以下jar加入到项目lib目录。tomcat.8080是tomcat自动生成的。logs是log4j自动生成的。

3、测试1。http://localhost:8088/esb/hi

package embed;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class EmbedTomcat {

  @SuppressWarnings("deprecation")
  public static void main(String[] args) {
    Tomcat tomcat = new Tomcat();
    
    HttpServlet servlet = new HttpServlet() {
      
      private static final long serialVersionUID = 3705103604036678076L;

      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
        resp.getWriter().write("a embeded tomcat");
      }
    };
 
    Context ctx = tomcat.addContext("/esb", null);
    Tomcat.addServlet(ctx, "/hi", servlet);
    ctx.addServletMapping("/hi", "/hi");
    
    try {
      tomcat.setPort(8088);
      tomcat.init();
      tomcat.start();
      tomcat.getServer().await();
    } catch (LifecycleException e) {
      e.printStackTrace();
    }
  }
}

4、测试2。http://localhost:8088/api/user_list
“C:\\java\\api”指定web目录。

package embed;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class EmbedTomcat {

  @SuppressWarnings("deprecation")
  public static void main(String[] args) {
    Tomcat tomcat = new Tomcat();
    
    try {
      // http://localhost:8088/api/user_list
      tomcat.addWebapp("/api", "C:\\java\\api");
      tomcat.setPort(8088);
      tomcat.init();
      tomcat.start();
      tomcat.getServer().await();
    } catch (LifecycleException e) {
      e.printStackTrace();
    }
  }
}

 

发表回复

您的电子邮箱地址不会被公开。