接着上一篇文章,这里举一个client端handler的例子。
先把webservice服务端的代码整个贴一下
webservice:
import javax.jws.HandlerChain; import javax.jws.WebMethod; import javax.jws.WebService; @WebService @HandlerChain(file="handlers.xml") public class HelloWS { @WebMethod public String sayHello(String name) { return "Hello " + name + "."; } }
handler:
import java.util.Set; import javax.xml.namespace.QName; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.handler.soap.SOAPHandler; import javax.xml.ws.handler.soap.SOAPMessageContext; public class HelloHandler implements SOAPHandler<SOAPMessageContext> { @Override public boolean handleMessage(SOAPMessageContext context) { System.out.println(context.get(MessageContext.WSDL_SERVICE).toString()); return true; } @Override public boolean handleFault(SOAPMessageContext context) { // TODO Auto-generated method stub return true; } @Override public void close(MessageContext context) { // TODO Auto-generated method stub } @Override public Set<QName> getHeaders() { // TODO Auto-generated method stub return null; } }
这里用j2se来发布webservice,主函数为:
import javax.xml.ws.Endpoint; public class ServerMain { /** * @param args */ public static void main(String[] args) { Endpoint.publish("http://localhost:8000/HelloWS3/HelloWSService",new HelloWS()); } }
运行主函数,可以发布webservice,wsdl地址为:http://localhost:8000/HelloWS3/HelloWSService?wsdl
生成客户端代码
用wsimport命令生成客户端代码
命令为:。。。/workspace/helloWS3Client/bin>wsimport -keep http://localhost:8000/HelloWS3/HelloWSService?wsdl -p com.ws.client
其中keep表示保存源文件,-p表示代码保存到指定包下。
然后在com.ws.client下新建一个客户端主函数,其中在客户端的webservice代理对象中插入handler,为了方便使用上面的同一个handler类,client端代码如下:
import java.util.List; import javax.xml.ws.Binding; import javax.xml.ws.BindingProvider; import javax.xml.ws.handler.Handler; import com.ws.handler.HelloHandler; public class ClientMain { /** * @param args */ public static void main(String[] args) { HelloWSService hs=new HelloWSService(); HelloWS hello= hs.getHelloWSPort(); Binding binding=((BindingProvider)hello).getBinding(); List<Handler> handlerChain=binding.getHandlerChain(); handlerChain.add(new HelloHandler()); binding.setHandlerChain(handlerChain); System.out.println(hello.sayHello("xxxxxxx")); } }
代码的作用是在bindingprovider对象的handlerchain中添加一个handler。
保持之前的服务端webservice运行着,然后运行这个客户端,可以在两个进程的控制台中同时打印被调用的webservice名字。
server:
2011-5-4 18:12:08 com.sun.xml.internal.ws.model.RuntimeModeler getRequestWrapperClass
信息: Dynamically creating request wrapper Class com.ws.service.jaxws.SayHello
2011-5-4 18:12:08 com.sun.xml.internal.ws.model.RuntimeModeler getResponseWrapperClass
信息: Dynamically creating response wrapper bean Class com.ws.service.jaxws.SayHelloResponse
{http://service.ws.com/}HelloWSService
{http://service.ws.com/}HelloWSService
client:
{http://service.ws.com/}HelloWSService
{http://service.ws.com/}HelloWSService
Hello xxxxxxx.s