How can I access the ServletContext from within a JAX-WS web service?
-
06-07-2019 - |
Question
I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?
Solution
The servlet context is made 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:
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
...
@Resource
private WebServiceContext context;
Then, you can access the servlet context using:
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
OTHER TIPS
If you use Maven add this dependency!!!
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
So I solved for avoid conflict error for get ServletContext INFO :
And in class method I use
@WebService(endpointInterface = "choice.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Resource
private WebServiceContext context;
public String sayHi(String text) {
HttpServletRequest request =(HttpServletRequest) context.getMessageContext().get(MessageContext.SERVLET_REQUEST);
System.out.println(request.getContextPath());
If the object you are trying to share is a file, say myFile.txt
you can use the method below:
The best way to do this that I use is:
Thread.currentThread().getContextClassLoader().getResource("myFile.txt").getPath()
This gives the path of any file myFile.txt
placed in /WEB-INF/classes/
directory inside the WebContent
folder of the WebApp.
In Eclipse JEE environment you need to keep the file myFile.txt
, that you may want to read within the Web Service, in the src
folder for it to be transported to the /WEB-INF/classes/
folder by the deployer.