Tomcat之嵌入式启动

一、为什么需要嵌入式Tomcat

1.部署复杂度  :要去频繁改server.xml
2.架构约束    :额外加载监听器、引擎、JSP等用不到的一些东西
3.微服务架构  :

二、使用嵌入式Tomcat

案例1:嵌入式tomcat启动一个servlet

1.加嵌入式tomcat依赖包
<dependencies>
        <!-- 嵌入式tomcat -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>8.5.34</version>
        </dependency>

        <!-- 嵌入式tomcat的jsp支持 -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>8.5.34</version>
        </dependency>
</dependencies>

2.嵌入式tomcat运行servlet
public class ServletDemo {
    public static void main(String[] args) throws LifecycleException {
    	//1.引入tomcat
        Tomcat tomcat = new Tomcat();

        //2.自定义servlet,专门处理http请求
        HttpServlet httpServlet = new HttpServlet() {
            @Override
            public void service(ServletRequest request, ServletResponse response) throws IOException {
                response.getWriter().write("hello world");
            }
        };        

        //3.部署应用
        Context context = tomcat.addContext("/demo", null);
        //4.往应用添加servlet
        tomcat.addServlet(context, "hello", httpServlet);
        //servlet映射
        context.addServletMappingDecoded("/hello", "hello");

        //5.启动tomcat
        tomcat.init();
        tomcat.start();
        tomcat.getServer().await();  //阻塞tomcat,等待请求过来(相当于双击startup.bat)
    }
}

3.测试: 浏览器输入 http://localhost:8080/demo/hello    输出hello world

案例2:嵌入式tomcat启动一个项目

public class WebAppDemo {
    public static void main(String[] args) throws Exception {
        //1.引入嵌入式tomcat
        Tomcat tomcat = new Tomcat();

        //2.部署项目
        tomcat.addWebapp("/test", "E:\\code\\newenergy-app-backend-ccw\\out\\production\\classes");

        //3.启动tomcat
        tomcat.init();
        tomcat.start();
        tomcat.getServer().await();
    }
}

测试: 浏览器输入http://localhost:8080/test/控制层访问路径
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飘然生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值