代码很简单,直接如下:
该demo下载地址为:
https://download.csdn.net/download/shenhaiyushitiaoyu/10801668
- 代码部分
//接口
package com.fei.demo.inter;
public interface WebInterface {
public String getUserInfo();
public String getUserAge(String age);
}
//实现类:
package com.fei.demo.impl;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import com.fei.demo.inter.WebInterface;
@WebService
public class WebInterfaceImpl implements WebInterface {
@Override
@WebMethod(operationName="getUserInfo")
public String getUserInfo() {
User user=new User("小明", 15, "中华科大");
System.out.println("进入getUserInfo方法!!");
return user.toString();
}
@Override
@WebMethod
public String getUserAge(String age) {
System.out.println("进入getUserAge方法!!");
return age;
}
//发布webservice
public static void main(String[] args) {
//必须写本地IP
String address = "http://localhost:8089/wsdemo/getInfo";
Endpoint.publish(address , new WebInterfaceImpl());
System.out.println("发布成功");
//运行后浏览器输入:http://localhost:8089/wsdemo/getInfo?wsdl
//即可得该webservice的wsdl文档
}
}
class User {
private String name;
private Integer age;
private String school;
public String getName() {
return name;
}
public void setName(String name) {this.name = name;}
public Integer getAge() {return age;}
public void setAge(Integer age) {this.age = age;}
public String getSchool() {return school;}
public void setSchool(String school) {this.school = school;}
public User(String name, Integer age, String school) {
super();
this.name = name;
this.age = age;
this.school = school;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", school=" + school + "]";
}
}
右键运行可以启动webservice服务,然后浏览器输入:
http://localhost:8089/wsdemo/getInfo?wsdl
就可以看到接口文档啦
- 简单测试:
用eclipse自带的webservice浏览器就可以测试:
在getUserAge方法上输入13,点击go即可返回13的信息,说明能调用成功!!
- 生成客户端
右键项目,选择properties,转到项目src目录下:
右键打开命令窗口:
输入:
wsimport -keep -p com.fei.client http://localhost:8089/wsdemo/getInfo?wsd
注:-p后跟包名
可以看到,正在生成代码。。。
生成后发现这里有代码:
说明客户端生成成功!
- 使用客户端:
另写个main方法即可:
package com.fei.test;
import com.fei.client.WebInterfaceImpl;
import com.fei.client.WebInterfaceImplService;
public class Test {
public static void main(String[] args) {
WebInterfaceImplService service=new WebInterfaceImplService();
WebInterfaceImpl webInterfaceImplPort = service.getWebInterfaceImplPort();
String userInfo = webInterfaceImplPort.getUserInfo();
System.out.println("获取到的信息: "+userInfo);
}
}
备注:包名路径如下: