内置tomcat使用servlet

本文详细介绍了如何使用Java代码启动Tomcat服务器并配置Servlet,包括设置端口、上下文路径、Servlet实例及映射,为理解Tomcat内部工作原理及自定义部署提供指导。

tomcat启动类

public class AppTomcat {
    public static void main(String[] args) throws LifecycleException {
        // 创建Tomcat应用对象
        Tomcat tomcat = new Tomcat();
        // 设置Tomcat的端口号
        tomcat.setPort(8080);
        // 是否设置Tomcat自动部署
        tomcat.getHost().setAutoDeploy(false);
        // 创建上下文
        StandardContext standardContext = new StandardContext();
        // 设置项目名
        standardContext.setPath("/sb");
        // 监听上下文
        standardContext.addLifecycleListener(new FixContextListener());
        // 向tomcat容器对象添加上下文配置
        tomcat.getHost().addChild(standardContext);
        // 创建Servlet
        tomcat.addServlet("/sb", "helloword", new HelloServlet());
        // Servlet映射
        standardContext.addServletMappingDecoded("/hello", "helloword");
        //启动tomcat容器
        tomcat.start();
        //等待
        tomcat.getServer().await();
    }
}

servlet类

public class HelloServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hellowrld");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

 

转载于:https://www.cnblogs.com/FlyBlueSky/p/9613611.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值