Monday, November 12, 2007

How To Access Session from a JAX-WS Web Service Implementation

Today, I had the need to take a peek into the HttpSession from inside a JAX-WS webservice implementation class. Normally, such an implementation has no access to the servlet API, and generally, I believe that is how it should be.

Anyway, I had the need, so this is how to do it:
import javax.annotation.Resource;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.jws.WebService;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;

@WebService(serviceName = "FooService")
public class FooImpl implements Foo {

@Resource
private WebServiceContext wsContext;

public void wsOperation() {
MessageContext msgContext = wsContext.getMessageContext();
HttpServletRequest request = (HttpServletRequest) msgContext.get(MessageContext.SERVLET_REQUEST);
HttpSession session = request.getSession();
// work with the session here ...
}
}
When the JAX-WS stack implementation you are running your web services on is deploying your web service endpoint, it will inject an instance of WebServiceContext into the impl instance. You can then ask it for a MessageContext, and from this get the request, session, response etc.

Beware though. By doing this, you are binding your implementation to knowledge about which transport mechanism, it is deployed on and accessed through. It could be something else than HTTP. On the other hand, I guess 99.9999% of all web service implementations are deployed on HTTP :-)

I have this working with CXF in version 2.0.1-incubator. The WebServiceContext class is only since JAX-WS 2.0 and the @Resource annotation is only from JEE5 and on.

3 comments:

Tech Per said...

A wise colleague of mine told me, that newer cxf's need this to make this work:

<import resource="classpath:META-INF/cxf/cxf-extension-jaxws.xml" />

session state webservice java said...

I write an article like this, but there is also other solution by using @HttpSessionScope

http://weblogs.java.net/blog/2006/10/17/bringing-state-back-web-services-httpsession-scope

rish said...

thanks for this post, its useful
just as a side note, this also works for JAX-RS services.