在开发java Web时,有时我们会使用嵌入式jetty来运行,项目完成后,如果能够直接运行war包从而启动jetty来运行war包那就非常完美了,本文将讲解如何在项目中整合jetty 9,并构造可执行的war包(打包前和打包后都能随时启动)。
1.首先添加jetty 9的依赖(本文暂时只用到了jetty的以下依赖,读者根据自己的项目需要增加)
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.7.v20150116</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>9.2.7.v20150116</version>
</dependency>
2.项目中使用jetty 9。
首先我封装了自己的JettyServer
public class EmbeddedServer {
//public static final Logger logger = LoggerFactory.getLogger(EmbeddedServer.class);
// private static final int DEFAULT_BUFFER_SIZE = 16192;
protected final Server server = new Server();
public EmbeddedServer(int port,String path) throws IOException{
this(port,path,false,null);
}
/**
* use war to start
* @param port
* @param isWar
* @param warPath
* @throws IOException
*/
public EmbeddedServer(int port,boolean isWar,String warPath) throws IOException{
this(port,null,isWar,warPath);
}
private EmbeddedServer(int port, String path,boolean isWar,String warPath) throws IOException {
Connector connector = getConnector(port);
server.addConnector(connector);
WebAppContext application = getWebAppContext(path,isWar,warPath);
server.setHandler(application);
server.setStopAtShutdown(true);
}
protected WebAppContext getWebAppContext(String path,boolean isWar,String warPath) {
WebAppContext application;
if(isWar){
application=new WebAppContext();
application.setWar(warPath);