参考:https://github.com/hengyunabc/executable-embeded-tomcat-sample
使用spring-boot-maven-plugin打包,按照spring-boot规范。
git:https://gitee.com/g-vic/jfinal_demo_for_maven_jar
效果:
代码改造:
bom:
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <version>1.3.3.RELEASE</version>
- <executions>
- <execution>
- <phase>package</phase>
- <goals>
- <goal>repackage</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
dependencies:
- <tomcat.version>8.0.32</tomcat.version>
- <dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-core</artifactId>
- <version>${tomcat.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-el</artifactId>
- <version>${tomcat.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-logging-juli</artifactId>
- <version>${tomcat.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-websocket</artifactId>
- <version>${tomcat.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.tomcat.embed</groupId>
- <artifactId>tomcat-embed-jasper</artifactId>
- <version>${tomcat.version}</version>
- </dependency>
Main:
- public class Main {
- public static void main(String[] args) throws ServletException, LifecycleException, IOException {
- String hostName = "localhost";
- int port = 80;
- String contextPath = "";
- String tomcatBaseDir = TomcatUtil.createTempDir("tomcat", port).getAbsolutePath();
- String contextDocBase = TomcatUtil.createTempDir("tomcat-docBase", port).getAbsolutePath();
- Tomcat tomcat = new Tomcat();
- tomcat.setBaseDir(tomcatBaseDir);
- tomcat.setPort(port);
- tomcat.setHostname(hostName);
- Host host = tomcat.getHost();
- Context context = tomcat.addWebapp(host, contextPath, contextDocBase, new EmbededContextConfig());
- context.setJarScanner(new EmbededStandardJarScanner());
- ClassLoader classLoader = Main.class.getClassLoader();
- context.setParentClassLoader(classLoader);
- // context load WEB-INF/web.xml from classpath
- context.addLifecycleListener(new WebXmlMountListener());
- tomcat.start();
- tomcat.getServer().await();
- }
- }
DemoConfig改造:
- public void configEngine(Engine me) {
- me.setBaseTemplatePath("static");
- me.setSourceFactory(new ClassPathSourceFactory());
- me.addSharedFunction("/common/_layout.html");
- me.addSharedFunction("/common/_paginate.html");
- }
静态文件: