package session.server; import javax.jws.*; import javax.xml.ws.WebServiceContext; import javax.annotation.Resource; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.xml.ws.WebServiceException; import javax.xml.ws.handler.MessageContext; import javax.servlet.http.HttpSession; @WebService public class Hello { /** * WebServiceContext is injected by the JAX-WS Runtime */ @Resource private WebServiceContext wsContext; /** * another way to inject WebServiceContext * make sure this is not a WebMethod * */ /* @WebMethod(exclude = true) @Resource public void initializeContext(WebServiceContext wsContext) { System.out.println("Setting WebServiceContext"); this.wsContext = wsContext; } */ public int getCounter() { MessageContext mc = wsContext.getMessageContext(); HttpSession session = ((javax.servlet.http.HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST)).getSession(); // Get a session property "counter" from context if (session == null) throw new WebServiceException("No session in WebServiceContext"); Integer counter = (Integer) session.getAttribute("counter"); if (counter == null) { counter = new Integer(0); System.out.println("Starting the Session"); } counter = new Integer(counter.intValue() + 1); session.setAttribute("counter", counter); return counter; } /** * Lifecycle method called before servicing any requests */ @PostConstruct @WebMethod(exclude = true) public void onBeginService() { System.out.println("Called onBeginService: Session test"); // Initialize resources need by the Service // .... } /** * Lifecycle method called before destroying the service instance */ @PreDestroy @WebMethod(exclude = true) public void onEndService() { System.out.println("Called onEndService: Session test"); // Clean up resources need by the Service // .... } }