main方法启动Tomcat

1.新建普通maven工程,添加tomcat核心依赖:

<dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-core</artifactId>
      <version>8.5.16</version>
    </dependency>

2.自定义servlet

package home.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        String pname = req.getParameter("pname");
        if (pname == null) {
            pname = "world";
        }
        PrintWriter pw = resp.getWriter();
        pw.write("<h1>Hello, " + pname + "!</h1>");
        pw.flush();
    }
}

3.设置tomcat启动相关配置

package home;

import home.servlet.HelloServlet;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

public class APP {

    public static void main(String[] args) throws Exception{

        Tomcat tomcat=new Tomcat();
        tomcat.setPort(8080);

        StandardContext standardContext = new StandardContext();
        //设置上下文路径
        standardContext.setPath("/demo");

        standardContext.addLifecycleListener(new Tomcat.FixContextListener());

        tomcat.getHost().addChild(standardContext);

        //配置servlet和映射,HelloServlet为自定义servlet
        tomcat.addServlet("/demo","index",new HelloServlet());
        //配置servlet路径
        standardContext.addServletMappingDecoded("/index","index");

        tomcat.start();

        tomcat.getServer().await();

    }
}

4.运行代码:出现如下内容说明启动成功

​
一月 29, 2023 11:41:51 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8080"]
一月 29, 2023 11:41:51 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
信息: Using a shared selector for servlet write/read
一月 29, 2023 11:41:51 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
一月 29, 2023 11:41:51 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/8.5.16
一月 29, 2023 11:41:51 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]

​

5.在浏览器输入:http://localhost:8080/demo/index?pname=Mary

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值