jetty三種啟動方式
阿新 • • 發佈:2019-01-10
今天把jetty稍微研究了一下,之前使用的全是tomcat,所以開始接觸jetty感覺有點彆扭,不過總算走了一遍,總結了三種啟動jetty的方式,
1,直接硬編碼方式,很簡單:
這裡需要說明的是你也可以將controller(處理使用者請求的servlet)作為一個物件直接在上面傳給hander,不過不建議這麼做。因為通過web.xml可以不影響我們正常的web開發流程,降低jetty與我們專案的耦合度。其他設定可以根據需要新增。public static void main(String[] args) { try { // 伺服器的監聽埠 Server server = new Server(8080); // 關聯一個已經存在的上下文 WebAppContext context = new WebAppContext(); // 設定描述,作為hander載入使用 context.setDescriptor("./web/WEB-INF/web.xml"); // 設定Web內容上下文路徑 context.setResourceBase("./webapp"); // 設定上下文路徑既訪問路徑的根路徑 context.setContextPath("/cheng"); server.setHandler(context); // 啟動 server.start(); server.join(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
2,通過載入jetty.xml和webdefault.xml配置檔案實現,
這種方式,可以將關鍵資訊從配置檔案讀取。個人覺得好點。public static void main(String[] args) { try { XmlConfiguration config = new XmlConfiguration(new FileInputStream("./jetty/jetty.xml")); Server server=(Server)config.configure(); ContextHandlerCollection handler = new ContextHandlerCollection(); WebAppContext webContext = new WebAppContext(); webContext.setContextPath("/cheng"); webContext.setDefaultsDescriptor("./jetty/webdefault.xml"); webContext.setResourceBase("src/main/webapp"); webContext.setDescriptor("src/main/webapp/WEB-INF/web.xml"); webContext.setClassLoader(Thread.currentThread().getContextClassLoader()); handler.addHandler(webContext); server.setHandler(handler); server.stop(); server.start(); server.join(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } }
3,通過maven外掛實現,所有jetty的配置也是在外掛中配,
上面三種本人試過,都可以通過,如有需要請根據自身需要做調整,再有就是上面jetty.xml9.0之前和之後的dtd配置是有區別的。<plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.6.v20141205</version> <configuration> <webApp> <contextPath>/cheng</contextPath> <descriptor>src/main/webapp/WEB-INF/web.xml</descriptor> <defaultsDescriptor>./jetty/webdefault.xml</defaultsDescriptor> </webApp> <stopKey>exit</stopKey> <stopPort>9090</stopPort> <webAppSourceDirectory>src/main/webapp</webAppSourceDirectory> <scanIntervalSeconds>1</scanIntervalSeconds> <!-- <connectors> <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector"> <port>8080</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> --> <httpConnector> <port>8080</port> </httpConnector> <requestLog implementation="org.eclipse.jetty.server.NCSARequestLog"> <filename>target/access.log</filename> <retainDays>90</retainDays> <append>false</append> <extended>false</extended> <logTimeZone>GMT+8:00</logTimeZone> </requestLog> <!-- <systemProperties> <systemProperty> <name>productionMode</name> <value>${productionMode}</value> </systemProperty> </systemProperties> --> </configuration> </plugin> </plugins>