Java开发Web Service客户端技巧:wsimport、jaxws

搭建一个简单的Web Service服务器

要想跑Web Service客户端,前提是要有个Web Service服务器。如果你已经有Web Service服务器,那么可以跳过这一步。如果没有,可以使用JAX-WS搭建一个简单的Web Service服务器。

{public String sayHello(String name) {return “Hello ” + name;}(String[] args) {HelloWorld helloWorld = new HelloWorld();String address = “http://localhost:8080/helloWorld”;Endpoint.publish(address, helloWorld);}}

直接启动程序运行main方法,即完成搭建了一个简单的Web Service服务器了。可以通过地址:8080/helloWorld?wsdl查看Web Service的WSDL。WSDL是用来告诉我们如何去调用这个Web Service。

wsimport命令

在JDK的安装目录的bin目录下,有一个wsimport.exe文件,如果是Linux系统也可以找到相应的wsimport文件。在配置好环境变量的情况下,可以使用wsimport命令生成Web Service客户端的Java代码。

wsimport -s D:\xxg -Xnocompile -p com.xxg.wsclient :8080/helloWorld?wsdl

参数介绍: -s 指定Java文件的生成目录 -p 指定Java的package -Xnocompile 不需要编译成class文件

命令执行完成后,在目标文件夹下会生成Web Service客户端Java代码:

使用生成的Java客户端:

(String[] args) throws MalformedURLException {HelloWorld helloWorld = new HelloWorldService(new URL(“http://test.kongzhong.com:8080/helloWorld?wsdl”)).getHelloWorldPort();System.out.println(helloWorld.sayHello(“xxg”)); // 输出”Hello xxg”}

以上程序即是一个简单的Web Service客户端,它会调用Web Service并输出返回结果。

jaxws-maven-plugin插件

以上客户端代码是通过wsimport命令生成,也可以通过Maven插件jaxws-maven-plugin来生成Web Service客户端Java代码。

在pom.xml中配置插件:

>jaxws-maven-plugin>><wsdlUrl>:8080/helloWorld?wsdl></plugin>

新版本的jaxws-maven-plugin插件groupId是org.jvnet.jax-ws-commons,而老版本的groupId是org.codehaus.mojo,这里选用的是目前最新版本2.3。

配置好插件后,运行Maven指令:

mvn jaxws:wsimport

也可以很方便的生成Web Service客户端Java代码。

整合Spring框架

Spring框架提供了对Web Service客户端良好的支持,,可以通过Spring来配置和管理Web Service客户端。

======>

以上配置项中,serviceInterface指定生成的代码中对应的Class,wsdlDocumentUrl执行WSDL路径,namespaceUri、serviceName、portName都可以在WSDL文件中找到。org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean需要依赖包spring-web.jar。

运行下面对Spring管理的Web Service客户端进行测试:

(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext(“classpath:applicationContext.xml”);HelloWorld helloWorld = context.getBean(“webservice”, HelloWorld.class);System.out.println(helloWorld.sayHello(“xxg”)); // 输出”Hello xxg”}

没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,

Java开发Web Service客户端技巧:wsimport、jaxws

相关文章:

你感兴趣的文章:

标签云: