内置tomcat使用
作者:互联网
需要引入的maven依赖
<properties> <tomcat.version>8.5.24</tomcat.version> </properties> <dependencies> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>${tomcat.version}</version> </dependency> </dependencies> <build> <finalName>Mytomcat</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>hope.redheart.wx.StartTomcat</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build>
main方法启动
public static void main(String[] args) throws ServletException, LifecycleException { int port = 80; if (args.length == 1) { port = Integer.parseInt(args[0]); } // 获取项目绝对路径 File webappPath = new File(System.getProperty("user.dir")); // 创建tomat容器 Tomcat tomcat = new Tomcat(); // 设置端口 tomcat.setPort(port); // 设置webapp目录 StandardContext sct = (StandardContext) tomcat.addWebapp("/", webappPath.getAbsolutePath()); //web项目路径 WebResourceRoot resourceRoot = new StandardRoot(sct); //被加载的资源文件路径 DirResourceSet dirResourceSet = new DirResourceSet(); dirResourceSet.setBase(new File("target/classes").getAbsolutePath()); dirResourceSet.setWebAppMount("/WEB-INF/classes"); dirResourceSet.setRoot(resourceRoot); dirResourceSet.setInternalPath("/"); //把项目设置到webapp中 resourceRoot.addPreResources(dirResourceSet); sct.setReloadable(false); sct.setResources(resourceRoot); tomcat.start(); System.out.println("Tomcat已在本地" + port + "端口启动!"); tomcat.getServer().await(); }
标签:resourceRoot,内置,tomcat,maven,sct,dirResourceSet,使用,new 来源: https://www.cnblogs.com/yjp372928571/p/11738944.html