WebService--jax

时间:2023-03-09 18:18:08
WebService--jax

使用javax.jws编写webservice服务:

服务端:

1,定义webservice接口:

package com.jws.serviceInterface;

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style=Style.RPC)
public interface HelloWorld {

String sayHi(@WebParam(name="text") String text);

}

2,实现webservice接口的(红色部分内容为接口文件,serviceName可自定义):

import javax.jws.WebService;

import com.jws.serviceInterface.HelloWorld;

@WebService(endpointInterface="com.jws.serviceInterface.HelloWorld",serviceName="HelloWorld")
public class HelloWorldImp implements HelloWorld {

@Override
public String sayHi(String text) {
// TODO Auto-generated method stub

return "say hi "+text;
}

}

3,发布webservice:使用Endpoint.publish进行发布,该种方法适用于将程序打包成jar运行的方式运行。

public static void main(String[] args) {

String address ="http://localhost:9000/service";
HelloWorld helloWorld = new HelloWorldImp();
Endpoint.publish(address, helloWorld);
}

发布成功后,通过访问http://localhost:9000/service/HelloWorld?wsdl可看到如下内容:

WebService--jax

客户端:

通过wsimport(jdk自带命令,如果找不到请检查jdk配置)命令导出Webservice接口文件到项目当中:

(pacakgeName:在客户端项目中webservice接口文件的包名,urlAddress:webservice访问地址,saveDir:保存本地路径)

wsimport -keep -p packageName urlAddress -s saveDir

例如:

 wsimport -keep -p com.jws.service http://localhost:9000/service/HelloWorld?wsdl -s D:/service/

导出工程后结构如下:

WebService--jax

客户端调用方式如下:

 

public static void main(String[] args) throws MalformedURLException {

HelloWorld helloWorld = new HelloWorld_Service(new URL("http://localhost:9000/service/HelloWorld?wsdl)).getHelloWorldImpPort();
String reply = helloWorld.sayHi("test");
System.out.println(reply);
}

调用方式可以直接写url地址,也可以将所有soap内容保存到本地,通过file:address方式进行引用。如果需要使用soap handler拦截器进行请求拦截,则只能使用本地文件引用的方式。