WebService(二):JWS API 开发

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014231646/article/details/80840365

    JAX-WS,即Java API for XML Web Service,是Java开发基于SOAP协议的Web Service的标准。使用JWS API就可以直接开发简单的Web Service应用。

一、创建Web Service

1、打开Eclipse,新建一个Java Project,如下图所示:


2、编写相关类

新建了“HelloWorld”一个接口,“User”、“HelloWorldImpl”、“JWSWebService”三个类,其中“User”是实体类,“HelloWorldImpl”继承自“HelloWorld”接口,“JWSWebService”类是主程序入口。

package com.guowei.ws.jws;
 
import javax.jws.WebParam;
import javax.jws.WebService;
 
/**
 * @author guowei
 *
 */
@WebService
public interface HelloWorld {
	 String sayHi(@WebParam(name="text") String text);
	 String sayHiToUser(@WebParam(name="user") User user);
}




package com.guowei.ws.jws;
 
/**
 * @author guowei
 *
 */
public class User {
	private String name;
	private String description;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}


package com.guowei.ws.jws;
 
import javax.jws.WebService;
 
@WebService(endpointInterface = "com.guowei.ws.jws.HelloWorld",serviceName = "HelloWorld")
public class HelloWorldImpl implements HelloWorld {
 
	public String sayHi(String text) {
		// TODO Auto-generated method stub
		System.out.println("sayHi called");
		return "Hello " + text;
	}
 
	public String sayHiToUser(User user) {
		// TODO Auto-generated method stub
		System.out.println("sayHiToUser called");
		return "Hello "+ user.getName() +user.getDescription();
	}
 

 
 
package com.guowei.ws.jws;
 
import javax.xml.ws.Endpoint;
 
public class JWSWebService {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Starting Server");
		HelloWorldImpl implementor = new HelloWorldImpl();
		String address = "http://localhost:9000/helloWorld";
		Endpoint.publish(address, implementor);
		System.out.println("Web Service started");
	}	
 
}

二、发布Web Service

运行JWSWebService,控制台出现如下提示,表明Web Service发布成功。


在浏览器地址栏中输入地址,出现如下界面,说明Web Service发布成功了。其中的内容则是Web Service的描述信息。


三、Java客户端调用Web Service

1、eclipse创建客户端




2、新建一个名为“com.guowei.ws.jwsclient”包,新建一个类“JWSClientDemo”,其代码如下:

package com.guowei.ws.jwsclient;
 
import com.guowei.ws.jws.HelloWorld;
import com.guowei.ws.jws.HelloWorld_Service;
import com.guowei.ws.jws.User;
 
public class JWSClientDemo {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HelloWorld_Service jwsService = new HelloWorld_Service();
		HelloWorld hw = jwsService.getHelloWorldImplPort();
		System.out.println(hw.sayHi("geek"));
		
		User user = new User();
		user.setName("Jobs");
		user.setDescription("apple");
		System.out.println(hw.sayHiToUser(user));
	}
 
}

3、运行程序,结果如下,说明成功调用Web Service。



参考:https://blog.csdn.net/u012719556/article/details/49666017

猜你喜欢

转载自blog.csdn.net/u014231646/article/details/80840365