Java Web 學習筆記之八:嵌入式web服務器Jetty的基本使用

Jetty 是一個開源的servlet容器,具有易用性,可擴展性,易嵌入性等特點。通過少量的代碼,開發者就可以在程序中以嵌入的方式運行一個web服務器。

 

下面介紹一些Jetty使用的方式:

 

方式一(直接在代碼中定義web應用的上下文):

1)新建maven工程,pom下的依賴如下圖:


(2)編寫自定義的一個Servlet類,用來測試,如下圖:


(3)編寫程序入口類main方法,如下圖:


(4)項目目錄結構如下圖:


以上三個步驟之後就可以運行main方法啓動程序了,可以看到控制檯輸出:


說明Jetty服務器啓動成功了。

 

下面測試一下剛纔編寫的BaseServlet,它的URLmain方法的配置中定義爲”/base”,可以看到結果如下:


說明Jetty成功將請求轉發給了自定義的servlet


方式一的main方法代碼如下:

public class Main {
	private static String host;
	private static String port;

	public static void main(String[] args) throws Exception {
		host = "127.0.0.1";
		port = "9681";
		InetSocketAddress address = new InetSocketAddress(host, Integer.parseInt(port));
		// 新建web服務器
		Server server = new Server(address);
		// 添加自定義的Servlet
		ServletContextHandler handler = new ServletContextHandler();
		handler.addServlet(BaseServlet.class, "/base");
		server.setHandler(handler);

		// 啓動web服務器
		server.start();
	}
}



方式二(利用web.xml配置文件定義web應用的上下文):

(1)新建maven工程,pom的依賴同方式一

(2)編寫自定義的BaseServlet,定義方式同方式一

(3)編寫web.xml配置文件(WebContent/WEB-INFO/),如下圖:

(4)編寫程序入口類main方法,如下圖:


(5)項目目錄結構如下圖:


運行main方法,並打開瀏覽器請求BaseServletURL,結果如下:



說明Jetty容器成功啓動並將請求轉發給了自定義的servlet


方式二的main方法代碼如下:

public class Main {
	private static String host;
	private static String port;

	public static void main(String[] args) throws Exception {
		host = "127.0.0.1";
		port = "9681";
		InetSocketAddress address = new InetSocketAddress(host, Integer.parseInt(port));
		// 新建web服務器
		Server server = new Server(address);
		// 配置web應用上下文
		WebAppContext webAppContext = new WebAppContext();
		webAppContext.setContextPath("/");
		// 設置配置文件掃描路徑
		File resDir = new File("./WebContent");
		webAppContext.setResourceBase(resDir.getCanonicalPath());
		webAppContext.setConfigurationDiscovered(true);
		webAppContext.setParentLoaderPriority(true);
		server.setHandler(webAppContext);
		// 啓動web服務器
		server.start();
	}
}

工程代碼連接:

利用Jetty服務器開發web應用例程


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章