`

Java开发Web Service客户端技巧:wsimport、jaxws-maven-plugin、整合Spring

阅读更多

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

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

@WebService
public class HelloWorld {

    public String sayHello(String name) {
        return "Hello " + name;
    }

    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorld();
        String address = "http://localhost:8080/helloWorld";
        Endpoint.publish(address, helloWorld);
    }
}

 

直接启动程序运行main方法,即完成搭建了一个简单的Web Service服务器了。可以通过地址http://localhost: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 http://localhost:8080/helloWorld

 

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

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



 

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

jaxws-maven-plugin插件

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

在pom.xml中配置插件:

<plugin>
    <groupId>org.jvnet.jax-ws-commons</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <packageName>com.xxg.wsclient</packageName>
        <sourceDestDir>src\main\java</sourceDestDir>
        <wsdlUrls>
            <wsdlUrl>
                http://localhost:8080/helloWorld?wsdl
            </wsdlUrl>
        </wsdlUrls>
    </configuration>
</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客户端。

<bean id="webservice" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
    <property name="serviceInterface" value="com.xxg.wsclient.HelloWorld" />
    <property name="wsdlDocumentUrl" value="http://localhost:8080/helloWorld?wsdl" />
    <property name="namespaceUri" value="http://wsserver.xxg.com/" />
    <property name="serviceName" value="HelloWorldService" />
    <property name="portName" value="HelloWorldPort" />
</bean>

 

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

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

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

 

  • 大小: 15 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics