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?
+8
A:
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:
@Resource
private WebServiceContext context;
Then, you can access the servlet context using:
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
Jens Bannmann
2008-11-04 09:39:38
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
2010-09-24 17:15:58
You should put this as a comment to an answer rather than as a separate answer
Ryan Fernandes
2010-05-17 05:26:21
A:
Saved my day.
But note, that it is accessible just after the ctor finished :(
So don't know how to figure out the applicationContext with not much boilerplate code...
Any ideas how to shorten this?
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
@WebService
public class MyWebService {
// boilerplate code begins :(
@Resource
private WebServiceContext context;
private WebApplicationContext webApplicationContext = null;
/**
* @return
* @throws IllegalStateException
*/
private WebApplicationContext getWebApplicationContext()
throws IllegalStateException {
if (webApplicationContext != null)
return webApplicationContext;
ServletContext servletContext =
(ServletContext) context.getMessageContext().get(
MessageContext.SERVLET_CONTEXT);
webApplicationContext =
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
return webApplicationContext;
}
}
pihentagy
2009-02-27 19:15:59
maybe you can use @PostConstruct to get the WebApplicationContext,so you getWebApplicationContext() is just one line.
Titi Wangsa bin Damhore
2010-08-15 09:24:11