Jetty实战之 maven+嵌入式Jetty运行web app

来源:互联网 发布:智能高清网络机顶盒 编辑:程序博客网 时间:2024/04/28 06:06

要说嵌入式运行Jetty,最常用的还应该是运行一个标准的war文件或者指定一个webapp目录。

0. 首先需要添加Jetty运行时webapp的依赖包,下面是一个完整的pom.xml文件

点击(此处)折叠或打开

  1. <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
  2.     xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>com.google.code.garbagecan.jettystudy</groupId>
  5.     <artifactId>jettystudy</artifactId>
  6.     <packaging>jar</packaging>
  7.     <version>1.0-SNAPSHOT</version>
  8.     <name>jettystudy</name>
  9.     <url>http://maven.apache.org</url>
  10.     <build>
  11.         <plugins>
  12.             <plugin>
  13.                 <artifactId>maven-compiler-plugin</artifactId>
  14.                 <inherited>true</inherited>
  15.                 <version>2.3.1</version>
  16.                 <configuration>
  17.                     <source>1.6</source>
  18.                     <target>1.6</target>
  19.                     <debug>true</debug>
  20.                 </configuration>
  21.             </plugin>
  22.         </plugins>
  23.     </build>
  24.     <dependencies>
  25.         <!-- Spring support -->
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring</artifactId>
  29.             <version>2.5.6</version>
  30.         </dependency>
  31.  
  32.         <!-- Jetty -->
  33.         <dependency>
  34.             <groupId>org.eclipse.jetty.aggregate</groupId>
  35.             <artifactId>jetty-all</artifactId>
  36.             <version>8.0.4.v20111024</version>
  37.         </dependency>
  38.  
  39.         <!-- Jetty Webapp -->
  40.         <dependency>
  41.             <groupId>org.eclipse.jetty</groupId>
  42.             <artifactId>jetty-webapp</artifactId>
  43.             <version>8.0.4.v20111024</version>
  44.         </dependency>
  45.  
  46.         <!-- JSP Support -->
  47.         <dependency>
  48.             <groupId>org.glassfish.web</groupId>
  49.             <artifactId>javax.servlet.jsp</artifactId>
  50.             <version>2.2.3</version>
  51.         </dependency>
  52.  
  53.         <!-- EL Support -->
  54.         <dependency>
  55.             <groupId>org.glassfish.web</groupId>
  56.             <artifactId>javax.el</artifactId>
  57.             <version>2.2.3</version>
  58.         </dependency>
  59.  
  60.         <!-- JSTL Support -->
  61.         <dependency>
  62.             <groupId>org.glassfish.web</groupId>
  63.             <artifactId>javax.servlet.jsp.jstl</artifactId>
  64.             <version>1.2.1</version>
  65.             <exclusions>
  66.                 <exclusion>
  67.                     <artifactId>jstl-api</artifactId>
  68.                     <groupId>javax.servlet.jsp.jstl</groupId>
  69.                 </exclusion>
  70.             </exclusions>
  71.         </dependency>
  72.     </dependencies>
  73. </project>

1. 运行标准的war文件

 

1.1 首先找一个完整的war包,这里使用了struts2自带的一个例子应用程序struts2-blank.war;

1.2 创建自己的Jetty Server启动类WebAppContextWithWarServer,其中指定了war文件的路径,并指定context路径为"/myapp"

点击(此处)折叠或打开

  1. package com.google.code.garbagecan.jettystudy.sample6;
  2.  
  3. import org.eclipse.jetty.server.Server;
  4. import org.eclipse.jetty.webapp.WebAppContext;
  5.  
  6. public class WebAppContextWithWarServer {
  7.     public static void main(String[] args) throws Exception {
  8.         Server server = new Server(8080);
  9.  
  10.         WebAppContext context = new WebAppContext();
  11.         context.setContextPath("/myapp\");
  12.         context.setWar("E:/share/test/struts2-blank.war");
  13.         server.setHandler(context);
  14.  
  15.         server.start();
  16.         server.join();
  17.     }
  18. }

1.3 运行WebAppContextWithWarServer类,然后访问// http://localhost:8080/myapp/就可以看到struts2的例子界面了。

 


2. 运行一个webapp目录

2.1 还是用上面的struts2-blank.war,将这个war包解压后放到一个目录下;

2.2 创建自己的Jetty Server启动类WebAppContextWithFolderServer,其中指定了webapp目录,并指定context路径为"/myapp"

点击(此处)折叠或打开

  1. package com.google.code.garbagecan.jettystudy.sample6;
  2.  
  3. import org.eclipse.jetty.server.Server;
  4. import org.eclipse.jetty.webapp.WebAppContext;
  5.  
  6. public class WebAppContextWithFolderServer {
  7.     public static void main(String[] args) throws Exception {
  8.         Server server = new Server(8080);
  9.  
  10.         WebAppContext context = new WebAppContext();
  11.         context.setContextPath("/myapp\");
  12.         context.setDescriptor("E:/share/test/struts2-blank/WEB-INF/web.xml");
  13.         context.setResourceBase("E:/share/test/struts2-blank");
  14.         context.setParentLoaderPriority(true);
  15.         server.setHandler(context);
  16.  
  17.         server.start();
  18.         server.join();
  19.     }
  20. }


2.3 运行WebAppContextWithFolderServer类,然后访问// http://localhost:8080/myapp/就可以看到struts2的例子界面了。

个人实践总结:
1、上面实例是介绍的绝对路径,但是如果想让jetty在项目中真正嵌入必须使用相对路径,要不移植性不高,以下是个人代码:

点击(此处)折叠或打开

  1. package com.sunny.server;
  2. import org.eclipse.jetty.server.Server;
  3. import org.eclipse.jetty.webapp.WebAppContext;
  4. public class JettyServer {
  5. public static void main(String[] args) {
  6. Server server = new Server(8080);
  7.        WebAppContext context = new WebAppContext();
  8.        context.setContextPath(\"/ext\");
  9.       String ProPath= System.getProperty(\"user.dir\");
  10.        context.setDescriptor(ProPath+\"/src/main/webapp/WEB-INF/web.xml\");
  11.        context.setResourceBase(ProPath+\"/src/main/webapp\");
  12.        context.setParentLoaderPriority(true);
  13.        server.setHandler(context);
  14.        try {
  15. server.start();
  16. server.join();
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }


2、如果想运行简单jsp页面必须加入<!-- JSP Support -->和<!-- EL Support -->下面的依赖包,其他的根据个人需要,以下是个人pom

点击(此处)折叠或打开

  1. <project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
  2. xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.sunnyit</groupId>
  5. <artifactId>ExtJsDemo</artifactId>
  6. <packaging>war</packaging>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>ExtJsDemo Maven Webapp</name>
  9. <url>http://maven.apache.org</url>

  10. <!-- 指定Maven仓库 -->
  11. <repositories>
  12. <repository>
  13. <snapshots>
  14. <enabled>true</enabled>
  15. </snapshots>
  16. <id>public</id>
  17. <name>Public Repositories</name>
  18. <url>http://192.168.17.x:8081/nexus/content/groups/public/</url>
  19. </repository>
  20. </repositories>
  21. <pluginRepositories>
  22. <pluginRepository>
  23. <id>public</id>
  24. <name>Public Repositories</name>
  25. <url>http://192.168.17.x:8081/nexus/content/groups/public/</url>
  26. </pluginRepository>
  27. </pluginRepositories>

  28. <properties>
  29. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  30. </properties>

  31. <dependencies>
  32. <dependency>
  33. <groupId>junit</groupId>
  34. <artifactId>junit</artifactId>
  35. <version>3.8.1</version>
  36. <scope>test</scope>
  37. </dependency>


  38. <!-- Jetty -->
  39. <dependency>
  40. <groupId>org.eclipse.jetty.aggregate</groupId>
  41. <artifactId>jetty-all</artifactId>
  42. <version>8.0.4.v20111024</version>
  43. </dependency>


  44. <!-- Jetty Webapp -->
  45. <dependency>
  46. <groupId>org.eclipse.jetty</groupId>
  47. <artifactId>jetty-webapp</artifactId>
  48. <version>8.0.4.v20111024</version>
  49. </dependency>

  50. <!-- JSP Support -->
  51.         <dependency>
  52.             <groupId>org.glassfish.web</groupId>
  53.             <artifactId>javax.servlet.jsp</artifactId>
  54.             <version>2.2.3</version>
  55.         </dependency>
  56.         
  57.         <!-- EL Support -->
  58.         <dependency>
  59.             <groupId>org.glassfish.web</groupId>
  60.             <artifactId>javax.el</artifactId>
  61.             <version>2.2.3</version>
  62.         </dependency>
  63. </dependencies>
  64. <build>
  65. <finalName>ExtJsDemo</finalName>
  66. </build>
  67. </project>


ApacheMaven是一个软件项目管理和理解工具。基于项目对象模型(POM)内容,Maven能够通过信息中心管理一个项目构建、报告和文档。它是一个理想的工具用来构建Web应用项目。这项目可以使用Jetty Maven插件在部署模式下运行Web应用。

       你能使用Maven来构建嵌入式Jetty应用程序和标准的基于Web应用。

为了理解使用Jetty构建和运行的基本操作,首先阅读:

1) Jetty HelloWorld教程

http://wiki.eclipse.org/Jetty/Tutorial/Jetty_HelloWorld

2) 嵌入Jetty教程

http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty

使用Maven配置嵌入式Jetty

       Maven使用约定优先于配置,因此最好使用Maven的项目结构,正如Maven推荐的。你能使用Archetypes快速设置Maven项目,但是对于本教程,我们将手动的设置结构:

mkdir JettyMavenHelloWorld

cd JettyMavenHelloWorld

mkdir -p src/main/java/org/example

创建HelloWorld类

       使用编辑器创建一个文件src/main/java/org/example/HelloWorld.java,内容如下:

package org.example;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

import javax.servlet.ServletException;

import java.io.IOException;

import org.eclipse.jetty.server.Server;

import org.eclipse.jetty.server.Request;

importorg.eclipse.jetty.server.handler.AbstractHandler;

 

public class HelloWorld extendsAbstractHandler

{

   public void handle(String target,

                       Request baseRequest,

                       HttpServletRequestrequest,

                       HttpServletResponseresponse)

       throws IOException, ServletException

    {

       response.setContentType("text/html;charset=utf-8");

       response.setStatus(HttpServletResponse.SC_OK);

       baseRequest.setHandled(true);

       response.getWriter().println("<h1>HelloWorld</h1>");

    }

 

   public static void main(String[] args) throws Exception

    {

       Server server = new Server(8080);

       server.setHandler(new HelloWorld());

 

       server.start();

       server.join();

    }

}

创建POM描述

       pom.xml声明项目名称及其依赖。使用编辑器创建一个pom.xml文件,内容如下:<project xmlns="http://maven.apache.org/POM/4.0.0"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">

 

 <modelVersion>4.0.0</modelVersion>

 <groupId>org.example</groupId>

 <artifactId>hello-world</artifactId>

 <version>0.1-SNAPSHOT</version>

 <packaging>jar</packaging>

 <name>Jetty HelloWorld</name>

 

 <properties>

   <jettyVersion>9.0.2.v20130417</jettyVersion>

 </properties>

 

 <dependencies>

   <dependency>

     <groupId>org.eclipse.jetty</groupId>

     <artifactId>jetty-server</artifactId>

     <version>${jettyVersion}</version>

   </dependency>

 </dependencies>

 

 <build>

   <plugins>

     <plugin>

       <!-- This plugin is needed for the servlet example -->

       <groupId>org.mortbay.jetty</groupId>

       <artifactId>jetty-maven-plugin</artifactId>

       <version>${jettyVersion}</version>

     </plugin>

     <plugin>

       <groupId>org.codehaus.mojo</groupId>

       <artifactId>exec-maven-plugin</artifactId>

       <version>1.1</version>

       <executions>

         <execution><goals><goal>java</goal></goals></execution>

       </executions>

       <configuration>

         <mainClass>org.example.HelloWorld</mainClass>

       </configuration>

     </plugin>

   </plugins>

 </build>

</project>

       注:使用9.0.2.v20130417版本可以找到下面的类:

importorg.eclipse.jetty.server.handler.AbstractHandler;

    但是使用Jetty的最新版本9.2.3.v20140905无法导入该类。

构建和运行嵌入式HelloWorld

       你现在能够使用下面的命令编译和执行HelloWorld类。

mvn clean compile exec:java

       你能使用浏览器打开http://localhost:8080看到Hello world页面。你能使用mvndependency:tree命令查看Maven幕后为你做了什么。它揭露解析和下载的依赖关系,如下:

> mvn dependency:tree

[INFO] Scanning for projects...

[INFO] Searching repository for plugin withprefix: 'dependency'.

[INFO] ------------------------------------------------------------------------

[INFO] Building Jetty HelloWorld

[INFO]   task-segment: [dependency:tree]

[INFO]------------------------------------------------------------------------

[INFO] [dependency:tree {execution:default-cli}]

[INFO]org.example:hello-world:jar:0.1-SNAPSHOT

[INFO] \-org.eclipse.jetty:jetty-server:jar:7.0.1.v20091125:compile

[INFO]   +- javax.servlet:servlet-api:jar:2.5:compile

[INFO]   +- org.eclipse.jetty:jetty-continuation:jar:7.0.1.v20091125:compile

[INFO]   \- org.eclipse.jetty:jetty-http:jar:7.0.1.v20091125:compile

[INFO]      \- org.eclipse.jetty:jetty-io:jar:7.0.1.v20091125:compile

[INFO]          \-org.eclipse.jetty:jetty-util:jar:7.0.1.v20091125:compile

[INFO] ------------------------------------------------------------------------

[INFO] BUILD SUCCESSFUL

[INFO]------------------------------------------------------------------------

[INFO] Total time: 4 seconds

[INFO] Finished at: Tue Feb 16 16:19:08 EST2010

[INFO] Final Memory: 11M/68M

[INFO]------------------------------------------------------------------------

使用Jetty和Maven开发标准WebApp

       上面的例子显示如何使用嵌入式Jetty处理器运行Hello world示例。下面的示例显示如何使用Maven和Jetty开发一个标准的WebApp。首先创建Maven结构。

mkdir JettyMavenHelloWarApp

cd JettyMavenHelloWarApp

mkdir -p src/main/java/org/example

mkdir -p src/main/webapp/WEB-INF

       创建静态内容:

       一个Web应用可以包含静态内容,因此创建文件src/main/webapp/index.html,内容如下:

<h1>Hello World Webapp</h1>

<a href="/hello">HelloServlet</a>

       创建一个Servlet

       使用编辑器创建src/main/java/org/example/HelloServlet.java,内容如下:

package org.example;

 

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class HelloServlet extendsHttpServlet

{

   protected void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException

    {

       response.setContentType("text/html");

       response.setStatus(HttpServletResponse.SC_OK);

       response.getWriter().println("<h1>HelloServlet</h1>");

       response.getWriter().println("session=" +request.getSession(true).getId());

    }

}

该Servlet需要在部署描述中声明,因此编译src/main/webapp/WEB-INF/web.xml,添加如下内容。

<?xml version="1.0"encoding="ISO-8859-1"?>

<web-app

  xmlns="http://java.sun.com/xml/ns/javaee"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

  version="2.5">

 <servlet>

   <servlet-name>Hello</servlet-name>

   <servlet-class>org.example.HelloServlet</servlet-class>

 </servlet>

 <servlet-mapping>

   <servlet-name>Hello</servlet-name>

   <url-pattern>/hello/*</url-pattern>

 </servlet-mapping>

</web-app>

       构建和运行Web应用:

       拷贝pom.xml,使用下面命令构建和运行Web应用。

mvn jetty:run

       你能在http://localhost:8080/hello-world/hello看到静态和动态的内容。内容的路径是url(hello-world)的一部分,来自于pom.xml文件中的人工ID。

构建WAR文件:

你能为项目创建一个WebApplication Archive(WAR)文件,使用命令:

mvn package

生成的war文件位于target目录中,你可以把它部署到标准servlet服务上或者部署到Jetty上。

启用SSL

       在嵌入式Jetty 9中启用SSL的过程如下:

       1)首先使用解释安全方案和端口的HTTP配置创建一个HttpConfiguration。

HttpConfiguration http_config = newHttpConfiguration();

http_config.setSecureScheme("https");

http_config.setSecurePort(8443);

       然后,我们为从上面的配置中扩展的https创建另外一个HttpConfiguration,但是添加一个SecureRequestCustomizer。

HttpConfiguration https_config = newHttpConfiguration(http_config);

https_config.addCustomizer(newSecureRequestCustomizer());

       3)接下来创建一个SslContexFactory指向你的JavaKeystore文件。

SslContextFactory sslContextFactory = newSslContextFactory("/its_dir/cert.keystore");

sslContextFactory.setKeyStorePassword("password");

       注意:你能使用OBF前缀密码,如果你打算使用Jetty模糊的密码。

     4)接下来我们创建一个ServerConnector,传递给它Server类,SslConnectorFactory和HttpConnectionFactory。如下:

ServerConnector httpsConnector = newServerConnector(server,

      new SslConnectionFactory(sslContextFactory, "http/1.1"),

      new HttpConnectionFactory(https_config));

httpsConnector.setPort(8443);

httpsConnector.setIdleTimeout(50000);      

       最后使用这个连接给服务,与正常的HTPP ServerConnector一样。

server.setConnectors(new Connector[]{httpsConnector });

与Jersey一起使用

官方网址:https://jersey.java.net/

文档网址:https://jersey.java.net/documentation/latest/index.html

下载网址:

       你能在代码中混合使用Jersey的2个版本,来自Jersey2.x(org.glassfish.jersey*包)中的ServletContainer和来自Jersey 1.x(包前缀com.sum.jersey.*)的属性。

       为了使用Jersey2.x开发你的应用,修改下面两行:

h.setInitParameter("com.sun.jersey.config.property.resourceConfigClass","com.sun.jersey.api.core.PackagesResourceConfig");

h.setInitParameter("com.sun.jersey.config.property.packages","resources");

       从main方法到下面函数中:

       h.setInitParameter(ServerProperties.PROVIDER_PACKAGES,"resources");

       并且检查其他ServerProperties,你可能找到有用的。


0 0
原创粉丝点击