how to create War file for a RESTful web service developed in eclipse IDE
I ve created a sample REST web service which writes some data in a xml file. Now I have hard coded the path where the xml file is to be written. I want to know how to declare that local path of the file in web.xml file as servlet parameter and how to get the path from there and use it in codebe . Also I need to create the WAR file for the service which needs to deployed in tomcat. This war file should take that parameter from the web.xml file. I used eclipse IDE to develop the web service. Can anyone tell me how to do the above things ?
Here I have attached the servlet code present inside the web.xml file.
<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>/ap开发者_StackOverflow社区i/*</url-pattern>
</servlet-mapping>
com.sample.service is the package where I have my Rest web service class.
Assuming you created this as a Dynamic Web project in Eclipse, just right-click on the
project name, > Export > WAR file
and fill in the details it asks for.
In your web.xml, you can define your filepath as below
<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>
*Updated with correct answer as per comments *
You're getting the NullPointerException on getServletContext().getInitParameter("filepath") because the Context is not injected into the web service method.
And in your web service, use this code to get the path and write to it using the @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
精彩评论