How To Access Session from a JAX-WS Web Service Implementation
Anyway, I had the need, so this is how to do it:
import javax.annotation.Resource;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.
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 ...
}
}
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.



0 kommentarer:
Post a Comment