Embed Tomcat 使用例程(9.0.12版本)
Tomcat作为Servlet容器和JSP容器,可以部署Web应用程序,但是有时候需要编写独立的前置程序,仅仅需要servlet,这个时候embed方式就很有用处了。
百度搜索结果,包括《Tomcat架构解析》书中给的,基本都运行不了,下面给出作者的样例程序。
第一步:下载9.0.12Embed版本,并将所有jar包引入eclipse工程。
package myTomcat;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
public class Testproc {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tomcat tomcat = new Tomcat();
HomeServlet myservlet = new HomeServlet();
Context context = tomcat.addContext("", null);
Tomcat.addServlet(context, "myservlet", myservlet);
context.addServletMappingDecoded("/", "myservlet");
System.out.println(tomcat.getConnector().getPort());
try {
tomcat.start();
} catch (LifecycleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tomcat.getServer().await();
}
}
程序HomeServlet.java
package myTomcat;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("request scheme: " + req.getScheme());
resp.getWriter().print("<h1>hello tomcat</h1>");
}
}
第二步:浏览器输入localhost:8080