Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Jetty Hello World:不用 Maven 也能跑起來的最小子專案

本文網址:https://wiki.eclipse.org/Jetty/Tutorial/Jetty_HelloWorld

這一章教你如何直接引用 CLASSPATH 下的 Jetty 類,用 Jetty API 寫出可執行的程式碼。如果你想走 Maven 或標準 Web 應用的路線,請參考 Jetty 與 Maven 的 HelloWorld 教學。

下載 Jar 包

Jetty 被拆分為許多 Jar 與依賴,挑最小集合能把記憶體佔用降到最低,實務上通常建議用 Maven 管理。不過本教學為了省事,使用聚合包 jetty-all,把所有 Jetty 類收錄在一個 Jar 裡:

mkdir Demo
cd Demo
JETTY_VERSION=9.2.3.v20140905
wget -U none https://repo1.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/$JETTY_VERSION/jetty-all-$JETTY_VERSION.jar
wget -U none https://repo1.maven.org/maven2/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar

撰寫 HelloWorld

嵌入式 Jetty 教學收錄了許多範例。這裡我們用最簡單的 HelloWorld Handler,在 main 方法中直接啟動服務:

package cn.uway.jetty;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class HelloWorld extends AbstractHandler {

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request,
                       HttpServletResponse response) 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();
    }
}

編譯

javac -cp servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar HelloWorld.java

執行

java -cp .:servlet-api-2.5.jar:jetty-all-$JETTY_VERSION.jar HelloWorld

接著在瀏覽器打開 https://localhost:8080,就能看到 Hello world 頁面。

下一步

  1. 閱讀 Jetty/Tutorial/Embedding Jetty 教學,認識更多 Jetty API: https://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty
  2. 翻閱完整的 Jetty Javadoc: https://download.eclipse.org/jetty/stable-7/apidocs/ 、 https://download.eclipse.org/jetty/stable-8/apidocs/ 、 https://download.eclipse.org/jetty/stable-9/apidocs/
  3. 考慮改用 Jetty 與 Maven 管理 Jar 與依賴: https://wiki.eclipse.org/Jetty/Tutorial/Jetty_and_Maven_HelloWorld
  4. 了解其他「如何用 Jetty 開發」的路線: https://wiki.eclipse.org/Jetty/Howto/Develop 、 https://wiki.eclipse.org/Jetty

延伸閱讀

使用 Jetty 作為嵌入式服務器 https://www.linuxidc.com/Linux/2013-07/86983.htm
Jetty 源碼分析 https://www.linuxidc.com/Linux/2013-10/90986.htm
Jetty 安裝學習並展示 https://www.linuxidc.com/Linux/2014-05/101993.htm
Jetty 在 Eclipse 中的安裝 https://www.linuxidc.com/Linux/2013-10/90991.htm
Linux(RedHat 5.8) 下 安裝 Jetty 部署 使用  https://www.linuxidc.com/Linux/2014-10/108342.htm

Copyright © Linux教程網 All Rights Reserved