2016-10-14 59 views
13

我創建了一個eclipse maven項目並添加了jetty依賴項。接下來我做了一個簡單的servlet和一個啓動碼頭服務器的類。這是我到目前爲止:使用web.xml以編程方式啓動jetty

package com.example.jetty; 

import org.eclipse.jetty.server.Server; 
import org.eclipse.jetty.servlet.ServletContextHandler; 

public class App { 
    public static void main(String[] args) throws Exception { 
     Server server = new Server(80); 
     ServletContextHandler servletContext = new ServletContextHandler(server, "/"); 
     servletContext.addServlet(MyServlet.class, "/"); 
     server.start(); 
    } 
} 

我的問題是,我看到的大多數教程有一個web.xml來配置servlets等。我找不到編程方法來完成其中的一些。我可以創建一個web.xml,並仍然以編程方式啓動我的碼頭,並以某種方式使用該web.xml進行配置?

更具體地說,我需要在web.xml中寫入true。我沒有找到任何方法來編程。

+0

爲什麼不使用maven來完成這項工作? Maven碼頭插件可以用作替代解決方案。 https://www.eclipse.org/jetty/documentation/9.4.x/jetty-maven-plugin.html – artificerpi

+0

嗡嗡聲......對我來說不太清楚。這種編程方式總是與聲明方式不同。你到底想做什麼? –

+0

更具體地說,我需要在web.xml中編寫 true。我沒有找到任何方法來編程。 – user1985273

回答

7

我將與您可能感興趣的一個例子說起。如果你想使用web.xml用編程的方式Jetty服務器,那麼你就可以做到以下幾點:。

WebAppContext context = new WebAppContext(); 
context.setContextPath("/myWebApp"); 
context.setExtractWAR(false); 
context.setDescriptor("/file/system/path/to/your/wab/app/WEB-INF/web.xml"); 
context.setResourceBase("/file/system/path/to/your/wab/app"); 
context.setConfigurationDiscovered(false); 

HandlerList handlerList=new HandlerList(); 
handlerList.addHandler(webAppContext); 

Server server = new Server(threadPool); 
server.setHandler(handlerList); 
server.start(); 

至於編程配置,你可以嘗試使用Servlet 3.x API,這是從Jetty 8.x(當前Jetty版本9.x)支持,並可以完全配置編程。

+0

謝謝anwser。我是否正確理解我需要這個servlet 3.x api依賴項,只有當我想以編程方式配置它時?你是否也知道如何使用這個API來配置異步支持的屬性的例子? – user1985273

+0

爲了啓用'Servlet 3.0',你需要在'web.xml'中指定'version =「3.0」'',所有的東西都可以留空,所以你可以在類路徑而不是文件系統中放置這樣的'web.xml'。 '@ WebServlet'參數'asyncSupported = true'可以用於'async-supported'。 –

+0

[這裏](https://github.com/jetty-project/embedded-servlet-3.1)你可以找到一個'Jetty'和'Servlet 3.0'的例子 –