不想经常打包部署,而想让WEB应用能直接Run As,Tomcat提供tomcat-embed-core-7.0.42.jar,故可以嵌入Tomcat。在Maven配置文件中添加如下的配置文件:
org.apache.tomcat
tomcat-catalina
7.0.42
org.apache.tomcat
tomcat-dbcp
7.0.42
org.apache.tomcat.embed
tomcat-embed-core
7.0.42
org.apache.tomcat.embed
tomcat-embed-logging-juli
7.0.42
org.apache.tomcat
tomcat-juli
7.0.42
org.apache.tomcat.embed
tomcat-embed-jasper
7.0.42
org.apache.tomcat
tomcat-jasper
7.0.42
org.apache.tomcat
tomcat-jasper-el
7.0.42
org.apache.tomcat
tomcat-jsp-api
7.0.42
引入的依赖的版本不一致,也能导致程序出现异常。故全部采用7.0.42,当然也可以采用其它版本,只是尽量保持一致。
写一个EmbeddedTomcat类,先看代码:
package com.raze.common.tomcat;
import java.io.File;
import javax.servlet.ServletException;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author DJM
*/
public class EmbeddedTomcat {
private Logger logger = LoggerFactory.getLogger(EmbeddedTomcat.class);
private Tomcat tomcat;
private int port;
private static final String tempDir= "src"+File.separatorChar+"main"+File.separatorChar+"webapp";
public EmbeddedTomcat(int port){
tomcat = new Tomcat();
this.port = port;
}
public void startUpTomcat(){
tomcat.setPort(port);
try {
tomcat.addWebapp("/DJM", System.getProperty("user.dir")+File.separatorChar+tempDir);
} catch (ServletException e) {
e.printStackTrace();
}
try {
StandardServer server = (StandardServer)tomcat.getServer();
AprLifecycleListener listener = new AprLifecycleListener();
server.addLifecycleListener(listener);
tomcat.start();
} catch (LifecycleException e) {
logger.info("An exception occurs when start tomcat!");
e.printStackTrace();
}
tomcat.getServer().await();
logger.info("Tomcat has been started successfully!");
}
public void shutDownTomcat(){
try {
tomcat.stop();
} catch (LifecycleException e) {
logger.info("An exception occurs when close tomcat!");
e.printStackTrace();
}
logger.info("Tomcat has been closed!");
}
}
有些资料指引我们使用org.apache.catalina.startup.Embedded,但是看下图就明白org.apache.catalina.startup.Embedded已经过时了,
所以采用org.apache.catalina.startup.Tomcat类。项目的目录结构如图:
我们现在调用我写的com.raze.common.tomcat.EmbeddedTomcat类,代码如下:
package com.raze;
import com.raze.common.tomcat.EmbeddedTomcat;
/**
* @author DJM
*/
public class Boot {
public static void main(String[] args) {
EmbeddedTomcat tomcat = new EmbeddedTomcat(8090);
tomcat.startUpTomcat();
}
}
直接Run As,选中JavaApplication,控制台打印如下信息:
选中项目,按"F5"或者右键"Refresh"项目,多出了一个与tomcat相关的目录,如下图:
成功嵌入Tomcat7。此处JSP页面中的Hello World也只为验证成功嵌入Tomcat7与否。