1. 程式人生 > >jetty搭建http伺服器

jetty搭建http伺服器

以前習慣於tomcat,相對而言,jetty也有很多優點,操作簡單,搭建http服務也很容易。

最近因為專案需要,需要直接啟動一個http server,供其它模組來調。具體如下:

1、去官網http://www.eclipse.org/jetty/下載jetty的包

2、新建一個java工程,將需要依賴的基本的jar拷貝到lib下面,包括:jetty-server.jar  jetty-servlet.jar  jetty-server  servlet-api.jar 具體版本號根據自己下載的jetty版本來定。

3、新建一個sever類,程式碼如下:

public class ServerMain {

	public static void main(String[] args) throws Exception {
		
		Server server = new Server(8090);
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/MyServer");   //這裡是請求的上下文,比如http://localhost:8090/MyServer
        server.setHandler(context);
        context.addServlet(new ServletHolder(new HelloWorld()), "/helloWorld");   //新增servlet,第一是具體的servlet,後面是請求的別名,在http請求中的路徑
        context.addServlet(new ServletHolder(new HelloWorld("chan")), "/HellworldWithParams");
        server.start();
        server.join();
	}
}
注意:這裡很奇怪的是Server中沒有start這個方法,start這個函式式Server的父類中定義的,我在官網上下載了7,8,9幾個版本都沒有這個方法,有點奇怪。當時沒有仔細去閱讀原始碼變更。無奈之下,又更換了jar包,這次是直接在http://search.maven.org/ 即Maven的中央倉庫下載的,搜尋jetty-all即可,裡面包含jetty相關所以的jar。重新替換jar包,最終需要引入兩個jar(jetty-all以及servlet-api.3.1.0.jar即可)結果Ok。

4、編寫HelloWorld這個Servlet,程式碼如下:

public class HelloWorld extends HttpServlet {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 2271797150647771294L;
	
	private String msg = "hello world~~~~~~";
	
	public HelloWorld() {
	}
	
	public HelloWorld(String msg){
		this.msg = msg;
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        resp.setStatus(HttpServletResponse.SC_OK);
        PrintWriter pWriter = resp.getWriter();
		pWriter.println("<h1>" + msg + "</h1>");
		pWriter.println("測試中文資訊:" + req.getSession(true).getId());
		pWriter.println("<h3>使用者資訊:" + userName + "</h3>");
		pWriter.println("<h3>使用者密碼:" + password + "</h3>");
	}
}
5、完了之後,在瀏覽器中輸入http://localhost:8090/MyServer/helloWorld?userName=zhangsan&password=123,得到的結果如下:
hello world~~~~~~

測試中文資訊:haybcp922h6x1v8bh9xeazx96
使用者資訊:zhangsan

使用者密碼:123

至此,一個基於jetty簡單的http服務就搭建起來了。