41

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?

Jens Bannmann
  • 4,845
  • 5
  • 49
  • 76

2 Answers2

45

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);
Jens Bannmann
  • 4,845
  • 5
  • 49
  • 76
  • 5
    If you're trying this on a JBoss EAP stack, and you start by creating a Seam project using the New Project Wizard in JBoss Developer Studio, you end up with a commons-annotations.jar file in your WEB-INF/lib (containing, among others, the @Resource annotation). The end result is that your WebServiceContext is not getting filled, and you get a NullPointerException. For us, the solution was simply to remove the commons-annotations.jar, to make sure that the JBoss-included version was used. After that, things went swimmingly. Thanks for the great answer, a real lifesaver! – László van den Hoek Sep 24 '10 at 17:15
  • 1
    Is there any other injectable resources other than the web service context ? – Muhammad Gelbana Aug 29 '13 at 21:32
2

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());
Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39