By default JAX-WS
web services and clients are stateless. When a client makes a request, the server responds and sets a cookie on the connection, if it participates in a session. But, the JAX-WS
client ignores that cookie and the server treats subsequent requests as new interaction. When the session is enabled, JAX-WS
client sends the same cookie with each subsequent request so that server can keep track of the client session.
So you should not be using either cookies or HTTP sessions with web services. Return a token ID as part of the response; then the client can send that along with the next request.
Anyway:
JAX-WS web service clients must be configured to maintain session information (such as cookies), using the javax.xml.ws.session.maintain
property.
Other web service stacks may have similar mechanisms.
On the Server Side
JAX-WS uses some handy annotations defined by Common Annotations for the Java Platform (JSR 250), to inject the web service context and declaring lifecycle methods.
WebServiceContext
holds the context information pertaining to a request being served.
You don't need to implement javax.xml.rpc.server.ServiceLifecycle
. With JAX-WS
Web Service all you need to do is mark a field or method with @Resource
. The type element MUST be either java.lang.Object
or javax.xml.ws.WebServiceContext
.
@WebService
public class HelloWorld {
@Resource
private WebServiceContext wsContext;
public void sayHello(){
MessageContext mc = wsContext.getMessageContext();
HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
}
}