一、为什么需要嵌入式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/控制层访问路径