一个特别好的Demo,记录一下
访问: http://127.0.0.1:8989/?name=name
package wang.jettyTest2; import org.eclipse.jetty.server.Server; public class JettyServer { public static void main(String[] args) throws Exception { //访问http://127.0.0.1:8989/?name=name Server server = new Server(8989); server.setHandler(new TestHandler()); server.start(); server.join(); } }
package wang.jettyTest2; import java.io.IOException; import java.io.PrintWriter; 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 TestHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //用户请求的uri //http://localhost:8080/index.html?name=rolin -> target=/index.html System.out.println("target is :" + target); //设置http头信息 response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); //获取向浏览器输出的流 PrintWriter out = response.getWriter(); if("/favicon.ico".equals(target)){//jetty默认会在每次请求结束,再请求一次这个uri System.out.println("request /favicon.ico"); out.write("404"); }else{ System.out.println("request other!"); //out.print("{['name':'name','id':'id']}"); out.print("<h3>hello jetty!</h3>"); //其他请求参数 if(request.getParameter("name") != null) { out.print("<h3>your name is "+request.getParameter("name")+"!</h3>"); } } } }