创建内嵌tomcat的java项目
一、在pom文件里添加内嵌版tomcat的依赖
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!-- 添加内嵌版tomcat --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>9.0.50</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>9.0.50</version> </dependency> <!-- 添加内嵌版tomcat -->
二、创建启动类如下
import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.webresources.DirResourceSet; import org.apache.catalina.webresources.StandardRoot; import java.io.File; /** * 项目启动类 */ public class Main { public static void main(String[] args) throws LifecycleException { // 启动 tomcat Tomcat tomcat = new Tomcat(); tomcat.setPort(Integer.getInteger("port", 8888)); tomcat.getConnector(); // 创建 WebApp Context context = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath()); WebResourceRoot resources = new StandardRoot(context); resources.addPreResources( new DirResourceSet(resources, "/WEB-INF/classes", new File("target/classes").getAbsolutePath(), "/")); context.setResources(resources); tomcat.start(); tomcat.getServer().await(); } }
三、启动项目访问8888端口