はじめに
http://blogs.yahoo.co.jp/dk521123/36139336.htmlhttp://blogs.yahoo.co.jp/dk521123/36140561.html
の続き。 上記の2つの関連記事を拡張し、今度はセッションを使用する * 以下のサイトに載っていることを上記の2つの関連記事のコードに組み込むだけ。https://docs.oracle.com/cd/E28613_01/web.1211/b65943/stateful.htm
サンプル
サーバサイドの実装
SampleWebService.javapackage com.sample.webservice; import javax.annotation.Resource; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.xml.bind.annotation.XmlElement; import javax.xml.ws.WebServiceContext; import javax.xml.ws.WebServiceException; import javax.xml.ws.handler.MessageContext; @WebService(name = "SampleWebService") public class SampleWebService { private static final String SESSION_KEY = "count"; @Resource private WebServiceContext webServiceContext; @WebMethod public String sayYourAge( @XmlElement(required = true, nillable = false) @WebParam(name = "name") String name, @XmlElement(required = false, nillable = true) @WebParam(name = "age") Long age) { // Find the HttpSession MessageContext messageContext = this.webServiceContext.getMessageContext(); HttpSession session = ((HttpServletRequest) messageContext.get(MessageContext.SERVLET_REQUEST)).getSession(); if (session == null) { throw new WebServiceException("No HTTP Session found"); } Integer counter = (Integer)session.getAttribute(SESSION_KEY); if (counter == null) { counter = new Integer(0); } else { counter++; } String returnValue; if (age == null) { returnValue = "[" + counter + "] SAY AGE!!"; } else { returnValue = "[" + counter + "] " + name + "'s age is " + age + "."; } session.setAttribute(SESSION_KEY, counter); return returnValue; } }
クライアントサイドの実装
Main.javapackage com.sample.webservice.client; import javax.xml.ws.BindingProvider; public class Main { public static void main(String[] args) { SampleWebServiceService service = new SampleWebServiceService(); SampleWebService proxy = service.getSampleWebServicePort(); ((BindingProvider) proxy).getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); String result = proxy.sayYourAge("Ken", 11L); System.out.println("Result1 : " + result); result = proxy.sayYourAge("Mike", null); System.out.println("Result2 : " + result); result = proxy.sayYourAge("Smith", 49L); System.out.println("Result3 : " + result); } }
出力結果
ちゃんとカウントアップされているResult1 : [0] Ken's age is 11. Result2 : [1] SAY AGE!! Result3 : [2] Smith's age is 49.