Jetty与Tomcat类似,也是一种Servlet引擎,可以用来运行Java Web项目。
其常被嵌入到项目中,以便于开发、测试,以及Demo等项目的运行。
1、作为插件——作为开发、测试时项目运行的容器
在Java Web APP开发中,为了测试功能是否如预期,通常需要编译、打包、部署三步骤,比较麻烦;虽开发时可在本地装Tomcat并在Eclipse中加以配置从而只需打包、运行两步,但若在其他机器开发又需要安装Tomcat,也比较麻烦。若能将Jetty和项目关联在一起就好了,借助Jetty我们可以达到这个目的。
方法:在Java Web项目的pom.xml中引入Jetty插件(如下),运行 mvn jetty:run 后访问http://localhost:8080
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.0.2.v20130417</version>
</plugin>
</plugins>
</build>
Normally, testing a web application involves compiling Java sources, creating a WAR and deploying it to a web container. Using the Jetty Plugin enables you to quickly test your web application by skipping the last two steps. By default the Jetty Plugin scans target/classes for any changes in your Java sources and src/main/webapp for changes to your web sources. The Jetty Plugin will automatically reload the modified classes and web sources.
2、作为依赖——嵌入在Java应用程序中,在Java程序中调用Jetty
依赖:
<!-- 已包含Servlet等需要用到的组件 -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>7.2.0.v20101020</version>
</dependency> <!-- 添加JSP依赖 -->
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jsp-2.1-glassfish</artifactId>
<version>2.1.v20100127</version>
</dependency>
静态Web:
public class Main_StaticWeb { public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub Server server = new Server(8080); ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase("src/main/resources/webcontent/static");
//resourceHandler.setDirectoriesListed(true);
server.setHandler(resourceHandler); server.start(); } }
动态Web:
public class Main_DynamicWeb { public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Server server = new Server(8080); WebAppContext webapp = new WebAppContext();
webapp.setWar("src/main/resources/webcontent/dynamic/");
//webapp.setWar("Cov.war");
server.setHandler(webapp); server.start();
server.join();
}
}
执行main方法后访问 http://localhost:8080 即可