Skip to main content

Maintaining Session With JAX-WS

Posted by ramapulavarthi on June 7, 2006 at 10:26 AM PDT

Web Services are stateless by default because of the underlying HTTP protocol. The server processes each web service request as a new interaction even though it is from the same client. To have a knowledge about previous requests, Server would need to maintain state about the client through some sort. Maintaining state/session would have extra load on the client/server in terms of time and memory. Even then, sometimes stateful web services can be useful for conversational message exchange patterns, where multiple message exchanges are required between client and server.

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.

Lets start off with a simple Counter Web Service which tracks the user requests. Each time client calls getCounter(), the service returns the counter after incrementing by 1.

public class Hello {
    int counter = 0;
    public int getCounter() {
        // incorrect     
Related Topics >>


Hi, your article is very

your article is very interesting, I do have one question though...
There's one concept that I'm still failing to understand, since the wsContext field is an instance field and since we have only one webservice class I would expect having race conditions when trying to retrieve session data from the field...
my question is practically, how is this achieved ? if two requests of two different sessions are retrieved at the server and both threads handling these requests perform the lines:

MessageContext mc = wsContext.getMessageContext();
HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
whilch session do we get ? do we get two different sessions for each thread ?

Hi, You do not have to worry about the synchronization/race ...

You do not have to worry about the synchronization/race condition for WebServiceContext object. Implementation will take care the of this, basically implementation will use thread local to make it thread safe.


Your example looks definitely

Your example looks definitely easy.
Do you think it would also so easy for a .NET client to enable session when calling a conversational java jax-ws web service ?
How would a c# snippet look like ?