該程序摘自官網教程;html
一、首先去Jetty官網,下載jetty-distribution-9.2.6.v20141205.zip,Jetty Jar包,解壓到任意目錄;java
二、使用Eclipse新建一個Java Project,命名爲helloworld-jetty;瀏覽器
三、選中工程,右鍵->properties->Java Build Path,獲得下圖:eclipse
四、按照上圖所標,選中Add Library->User Library->User Libraries->New,獲得下圖,輸入用戶庫名稱,如jetty-lib-9.2.6;jsp
選中剛添加的jetty-lib-9.2.6庫,選擇Add External JARs,將剛剛解壓獲得的jetty-distribution-9.2.6.v20141205\lib下的Jar包和jetty-distribution-9.2.6.v20141205\lib\jsp下的Jar包添加到該用戶庫下,點擊OK,將jetty-lib-9.2.6庫引入該工程。ui
五、建立HelloWorldJetty類,如下類摘自官網教程,只是改動了一下類名。spa
1 package org.example; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.eclipse.jetty.server.Request; 10 import org.eclipse.jetty.server.Server; 11 import org.eclipse.jetty.server.handler.AbstractHandler; 12 13 public class HelloWorldJetty extends AbstractHandler{ 14 15 public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) 16 throws IOException, ServletException{ 17 18 response.setContentType("text/html;charset=utf-8"); 19 response.setStatus(HttpServletResponse.SC_OK); 20 baseRequest.setHandled(true); 21 response.getWriter().println("<h1>Hello World</h1>"); 22 } 23 24 public static void main(String[] args) throws Exception{ 25 Server server = new Server(8080); 26 server.setHandler(new HelloWorldJetty()); 27 28 server.start(); 29 server.join(); 30 } 31 }
六、右鍵運行該工程,Run As Java Application,使用瀏覽器訪問http://localhost:8080/地址,可看到。code