2010-10-07 29 views
0

我創建了一個示例REST Web服務,它將一些數據寫入xml文件。現在我已經硬編碼了xml文件要寫入的路徑。我想知道如何將web.xml文件中的文件的本地路徑聲明爲servlet參數,以及如何從那裏獲取路徑並在代碼中使用它。另外我需要爲需要在tomcat中部署的服務創建WAR文件。這個war文件應該從web.xml文件中獲取該參數。我使用eclipse IDE來開發Web服務。誰能告訴我如何做到上述事情?如何爲在eclipse IDE中開發的REST風格的Web服務創建War文件

這裏我附加了web.xml文件中存在的servlet代碼。

<servlet> 
    <servlet-name>Jersey REST Service</servlet-name> 
<servlet-class> 
    com.sun.jersey.spi.container.servlet.ServletContainer 
</servlet-class> 
<init-param> 
    <param-name>com.sun.jersey.config.property.packages</param-name> 
    <param-value>com.sample.service</param-value> 
    </init-param> 
    <init-param> 
    <param-name>filepath</param-name> 
    <param-value>filepath value</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 
<servlet-mapping> 
    <servlet-name>Jersey REST Service</servlet-name> 
    <url-pattern>/api/*</url-pattern> 
</servlet-mapping> 

com.sample.service是我有我的休息Web服務類的包。

回答

2

假設您創建此作爲在Eclipse動態Web項目,在

項目名稱,只需右鍵單擊,>導出> WAR文件

,並在它要求填寫詳細信息。

在你的web.xml中,你可以定義你的文件路徑如下

<servlet> 
<servlet-name>MyServletName</servlet-name> 
<servlet-class>com.mycompany.MyServlet</servlet-class> 
<init-param> 
<param-name>filepath</param-name> 
<param-value>D:\hard-coded-path.xml</param-value> 
</init-param> 
</servlet> 

* 與正確答案更新按照意見*

擾得的getServletContext的NullPointerException異常()。 getInitParameter(「filepath」)是因爲Context沒有注入到Web服務方法中。

並在Web服務,使用此代碼來獲取路徑,並使用@Context annotation

@GET 
@Produces("text/plain") 
public String doStuff(@Context ServletConfig sc) { 



    String xmlpath = "Output filepath is: " + sc.getInitParameter("filepath"); 
    return xmlpath; 
} 

See here for usage and examples of @Context

+0

你好JoseK寫入。感謝您的迴應。正如你所說,我修改了web.xml並編寫了上述代碼,以獲取HttpServlet類的doGet方法中的路徑並創建了WAR文件。我可以知道如何運行這個戰爭文件嗎?我正在嘗試在Eclipse的IDE? – Senthil 2010-10-07 11:10:59

+0

您可以直接從Eclipse運行它。右鍵單擊項目>運行方式>在服務器上運行。您必須首先通過「Run configruations」在Eclipse中配置Tomcat服務器。 – JoseK 2010-10-07 11:13:07

+0

Hello JoseK。其實我正在寫入服務器端的XML即ie。在RESTful Web服務上。我想知道如何訪問REST Web服務類即web.xml中存在的文件路徑。裏面的REST方法。但我無法訪問Web服務中的ServletConfig對象。你能告訴我該怎麼做嗎? – Senthil 2010-10-07 11:22:22