欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webservice 第一讲

程序员文章站 2022-05-23 09:48:51
...
1.服务器的建立
1.1 创建接口
package org.first.service;

import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService
public interface IMyService {
	
	@WebResult(name="addResult")
	public int add(@WebParam(name="a")int a,@WebParam(name="b")int b);
	
	@WebResult(name="minusResult")
	public int minus(@WebParam(name="a")int a,@WebParam(name="b")int b);
	
	@WebResult(name="loginUser")
	public User login(@WebParam(name="username")String username,@WebParam(name="password")String password);

}

1.2 创建接口实现类
package org.first.service;

import javax.jws.WebService;

@WebService(endpointInterface="org.first.service.IMyService")
public class MyServiceImpl implements IMyService {

	@Override
	public int add(int a, int b) {
		System.out.println(a+"+"+b+"="+(a+b));
		return a+b;
	}

	@Override
	public int minus(int a, int b) {
		System.out.println(a+"-"+b+"="+(a-b));
		return a-b;
	}

	@Override
	public User login(String username, String password) {
		System.out.println(username+" is logining");
		User user = new User();
		user.setId(1);
		user.setUsername(username);
		user.setPassword(password);
		return user;
	}

}

1.3 开启服务
package org.first.service;

import javax.xml.ws.Endpoint;

public class MyServer {

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

}

2 客户端建立
package org.first.service;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class TestClient {
	public static void main(String[] args) {
		try {
			//创建访问wsdl服务地址的url
			URL url = new URL("http://localhost:8888/ns?wsdl");
			//通过Qname指明服务的具体信息
			QName sname = new QName("http://service.first.org/", "MyServiceImplService");
			//创建服务
			Service service = Service.create(url,sname);
			//实现接口
			IMyService ms = service.getPort(IMyService.class);
			System.out.println(ms.login("wxh", "wr"));
			//以上服务有问题,依然依赖于IMyServie接口
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}
相关标签: webservice