Java Reference
In-Depth Information
quests coming from the same client. Let's look at an example. First you need to create the
service, as shown in Example 7-16 .
Example7-16.Stateful web service using WebServiceContext
package com.soacookbook;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
@WebService
public class CounterContextWS {
@Resource
private WebServiceContext wsContext;
public int getCounter(){
MessageContext mc = wsContext.getMessageContext();
HttpSession session =
((javax.servlet.http.HttpServletRequest)mc.get(
MessageContext.SERVLET_REQUEST)).getSession();
Integer count = (Integer)session.getAttribute("count");
if (count == null) {
count = 0;
System.out.println("New Session ID=" + session.getId());
}
count++;
session.setAttribute("count", count);
return count;
}
}
Here you take advantage of auto-boxing and auto-unboxing of the counter primitive. The ser-
vice class simply stores the session in the WebServiceContext . The counter associated with
the given session is stored as an attribute, like you would a shopping cart item or anything else
in a servlet session. But you're not done yet. Notice that in the service the count variable is
method local. You can't just store it as an instance variable, for the same reason you couldn't
with a regular servlet. While it would appear to work in a simple test, multiple clients would
get the shared variable.
At this point, if a client invokes the service in the regular fashion, the counter would not ap-
pear to increment. That's because the session ID is not being sent along with each request, so
Search WWH ::




Custom Search