Start a tomcat using the Main method

Source: Internet
Author: User
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 ')


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.