Access ServletContext from within a JAX-WS Web Service

In a typical J2EE project, we put the application level initial parameter in context-param tag in web.xml, such as database configuration, administrator's email address, etc.

The values within the element can be accessed like so:

String value = 
getServletContext().getInitParameter("name_of_context_initialization_parameter");

When dealing with Web Service, the same problem comes up.

What if we want to put database configuration information in a configuration file, and let Web Service access it? We want the configuration info is not hard-coded, and therefore can be changed during the deployment stage.

Luckily for us, the servlet context can be access by Web Service too. Servlet Context is available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service:

@Resource
private WebServiceContext context;

Then, you can access the servlet context using:

ServletContext servletContext =
    (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);

What about other ways to put configuration information for Java Web Service?

Category >> JSP/JSF >> Web Services  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • admin

    Thanks for your comment.

    I think when a war file is deployed to the server, a ServletContext is initialized. So you can access it. Since it is accessed through a web service method, whenever you call a method, the value is got through that call.

    The problem is: is this the right way to do it?

  • Daniel Manzke

    But this way is only possible, while processing a request. How would you solve it, when you want to initialize it, before there is a request?

    Greetings,
    Daniel