Jetty实战之 嵌入式运行Jetty
1.创建一个Server类,用了启动Jetty server,并且通过一个HelloHandler来处理浏览器发送过来的请求;
package com.google.code.garbagecan.jettystudy.sample1;
import org.eclipse.jetty.server.Server;
public class MyServer {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
server.setHandler(new HelloHandler());
server.start();
server.join();
}
}
2.创建一个Handler类,用了处理所有客户端的请求
package com.google.code.garbagecan.jettystudy.sample1;
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.handler.AbstractHandler;
public class HelloHandler extends AbstractHandler {
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("
Hello World
");response.getWriter().println("Request url: " + target);
}
}
3.运行MyServer类,然后通过浏览器访问http://localhost:8080/,可以看到“Hello World!”和请求的url。