Jetty实践-Hello World

该程序摘自官网教程

1、首先去Jetty官网,下载jetty-distribution-9.2.6.v20141205.zip,Jetty Jar包,解压到任意目录;

2、使用Eclipse新建一个Java Project,命名为helloworld-jetty;

3、选中工程,右键->properties->Java Build Path,得到下图:

4、按照上图所标,选中Add Library->User Library->User Libraries->New,得到下图,输入用户库名称,如jetty-lib-9.2.6;

选中刚添加的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库引入该工程。

5、创建HelloWorldJetty类,以下类摘自官网教程,只是改动了一下类名。

 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 }

 

6、右键运行该工程,Run As Java Application,使用浏览器访问http://localhost:8080/地址,可看到。

posted @ 2014-12-25 17:39  _crazysnail_  阅读(1226)  评论(0编辑  收藏  举报