views:

3795

answers:

2

Hi all,

I am new to java so excuse my lame questions:)

I am trying to build a web service in Java NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net).

What is the right way to save and access such settings in a java web service.

Is there a way to read context parameters from web.xml in a web method?

If no what are the alternatives for storing your configuration variables like pathnames ?

Thank you

+2  A: 

If you are using servlets, you can configure parameters in web.xml:

<servlet>
  <servlet-name>jsp</servlet-name>
  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
      <param-name>fork</param-name>
      <param-value>false</param-value>
     </init-param>
</servlet>

These properties will be passed in a ServletConfig object to your servlet's "init" method.

Another way is to read your system's environment variables with

System.getProperty(String name);

But this is not recommended for other than small programs and tests.

There is also the Properties API if you want to use ".properties" files. http://java.sun.com/javase/6/docs/api/java/util/Properties.html

Finally, I believe looking up configurations with JNDI is pretty common when developing modern web service applications, Netbeans and app containers have pretty good support for that. Google it.

Lars Westergren
Please read the question more carefully. You should give a specific answer to the specific question: "Access web.xml context parameters from Web Service method?".Nevertheless you give some useful alternatives.
Mulmoth
+2  A: 

Is there a way to read context parameters from web.xml in a web method?

No, this is not easily done using the out-of-the-box. The Web Service system (JAX-WS) has minimal awareness of the Servlet engine (Tomcat). They are designed to be isolated.

If you wanted to use the context parameters, your web service class would need to implement ServletContextListener and retrieve the desired parameters in the initialization parameter (or save the context for later use). Since the Servlet engine and JAX-WS would each have different instances of the object, you'd need to save the values to a static member.

As Lars mentioned, the Properties API or JNDI are your best bets as they're included with Java and are fairly well-known ways to retrieve options. Use Classloader.getResource() to retrieve the Properties in a web context.

James Schek
Thanks James for pointing out how this can be achieved.
Mulmoth