Jetty 简单使用

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 

1     <build>
2         <plugins>
3             <plugin>
4                 <groupId>org.eclipse.jetty</groupId>
5                 <artifactId>jetty-maven-plugin</artifactId>
6                 <version>9.0.2.v20130417</version>
7             </plugin>
8         </plugins>
9     </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

依赖:

 1         <!-- 已包含Servlet等需要用到的组件 -->
 2         <dependency>
 3             <groupId>org.eclipse.jetty</groupId>
 4             <artifactId>jetty-webapp</artifactId>
 5             <version>7.2.0.v20101020</version>
 6         </dependency>
 7 
 8         <!-- 添加JSP依赖 -->
 9         <dependency>
10             <groupId>org.mortbay.jetty</groupId>
11             <artifactId>jsp-2.1-glassfish</artifactId>
12             <version>2.1.v20100127</version>
13         </dependency>

静态Web:

 1 public class Main_StaticWeb {
 2 
 3     public static void main(String[] args) throws Exception {
 4         // TODO Auto-generated method stub
 5 
 6         Server server = new Server(8080);
 7 
 8         ResourceHandler resourceHandler = new ResourceHandler();
 9         resourceHandler.setResourceBase("src/main/resources/webcontent/static");
10         //resourceHandler.setDirectoriesListed(true);
11         server.setHandler(resourceHandler);
12 
13         server.start();
14 
15     }
16 
17 }
View Code

动态Web:

 1 public class Main_DynamicWeb {
 2 
 3     public static void main(String[] args) throws Exception {
 4         // TODO Auto-generated method stub
 5         Server server = new Server(8080);
 6 
 7         WebAppContext webapp = new WebAppContext();
 8         webapp.setWar("src/main/resources/webcontent/dynamic/");
 9         //webapp.setWar("Cov.war");
10         server.setHandler(webapp);
11 
12         server.start();
13         server.join();
14     }
15 }
View Code

 执行main方法后访问  http://localhost:8080  即可

 

原文地址:https://www.cnblogs.com/z-sm/p/5866502.html