Package org.huluo.embedTomcat;
Import org.apache.catalina.LifecycleException;
Import Org.apache.catalina.core.StandardContext;
Import Org.apache.catalina.startup.Tomcat;
Import java.io.IOException;
public class Main {public
static void Main (string[] args) throws Lifecycleexception, IOException {
tomcat tomcat = new Tomcat ();
Tomcat.sethostname ("localhost");
Tomcat.setport ();
Tomcat.setbasedir ("E:/embedtomcat");
String contextpath = "";
Standardcontext context = new Standardcontext ();
Context.setpath (contextpath);
Context.addlifecyclelistener (New Tomcat.fixcontextlistener ());
Tomcat.gethost (). AddChild (context);
Tomcat.addservlet (ContextPath, "Hello", New Embedtomcatservlet ());
context.addservletmappingdecoded ("/hello", "Hello");
Tomcat.start ();
Tomcat.getserver (). await ();
}
This allows you to start an embedded Tomcat in the form of a Main method
But we don't have a servlet yet:
In writing a servlet, the servlet only prints a line on the page HelloWorld
Package org.huluo.embedTomcat;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import java.io.IOException;
public class Embedtomcatservlet extends HttpServlet {
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {this.dopost
(req, resp);
@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
resp.getwriter (). Write ("HelloWorld");
}
and add the embedded Tomcat dependency pack OH
Compile (group: ' org.apache.tomcat.embed ', Name: ' Tomcat-embed-core ', version: ' 8.5.14 ')