Java Reference
In-Depth Information
Providing Stateful Services
Problem
You want your web service to keep track of client sessions, much as you could do with a ser-
vlet.
Solution
This is a tricky one—at least as of this writing. There are a few different solutions, none of
them is optimal. Here are your options:
▪ If you are using HTTP as the transport layer, declare a WebServiceContext object as a
Resource , and use it to get the HttpSession object. Use the HttpSession as you nor-
mally would in a servlet. The only downside is that it does not work for transports other
than HTTP. But it's straightforward and portable.
▪ If you are using the JAX-WS reference implementation, you can use a simple annotation,
@HttpSessionScope . This is a nice solution that wraps the first solution just mentioned,
so there is a little less coding. There is no need to do anything but store your desired state
in regular instance variables, and the runtime will hand out one service instance per HTTP
session. However, it is specific to the RI and it does not work just yet. (See https://jax-
ws.dev.java.net/issues/show_bug.cgi?id=545 . )
▪ Finally, you can use WS-Addressing, which works outside of HTTP, but this is very com-
plex. WS-Addressing is outlined in Chapter 12 .
Discussion
HTTP is a stateless protocol, meaning that each new connection bears no relation to any pre-
vious connection; state is not held between requests. While this is a fundamental feature of
HTTP, there are many times when keeping state (particular knowledge of each request as it
relates to other requests from the same client) is necessary. It's this mechanism that allows
you to store items in a shopping cart, for example.
Using WebServiceContext
Let's examine keeping state using the WebServiceContext object, which is similar to the
ServletContext object in a web container. You can declare the context as a Resource to be
injected by the container, and then use it to store data that you want to associate with all re-
Search WWH ::




Custom Search