Jetty和Maven HelloWorld

       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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值