本文網址:https://wiki.eclipse.org/Jetty/Tutorial/Jetty_HelloWorld
這一章教你如何直接引用 CLASSPATH 下的 Jetty 類,用 Jetty API 寫出可執行的程式碼。如果你想走 Maven 或標準 Web 應用的路線,請參考 Jetty 與 Maven 的 HelloWorld 教學。
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
嵌入式 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 頁面。
使用 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