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
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?
You may also like:
Leave a comment
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
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?