利用javax包下的Endpoint类的静态方法publish(“发布地址”,new Object());发布一个webService服务,需要以下几步:
1、要发布的类或者接口必须使用javax.jws的@WebService标注该类或者接口,表示该类或者接口提供WebService服务。代码如下:
package com.webService.test;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.util.Date;
/**
* 这个类将被作为webService服务被远程调用
* 必须注明是WebService服务:@WebService
*/
@WebService
public class MyService {
public String myDoublePrintByInput(String inputStr){
return DoublePrint.doublePrintByInput(inputStr);
}
public String myDateToString(Date time){
return DateToString.dateToString(time);
}
//当此类执行时发布webService服务
public static void main(String[] args){
//publish的第一个参数表示服务地址,第二个参数是服务对象
Endpoint.publish("http://localhost:9002/Service/MyServiceTest",new MyService());
System.out.println("is Success?");
}
}
2、在命令窗口使用如下指令:wsimport -keep -p com.demo.client http://localhost:9002/Service/MyServiceTest?wsdl
注:将根目录选择为D或者E、F盘,方便找到生成的客户端文件
3、将生成的文件夹拷贝到新建项目的src下,写测试类,测试成功OK!测试类如下:
package com.testService.client.test;
import com.testService.client.MyService;
import com.testService.client.MyServiceService;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 客户端测试类
*/
public class Test {
public static void main(String[] args){
MyServiceService mss = new MyServiceService();
MyService ms = mss.getMyServicePort();
System.out.println(ms.myDoublePrintByInput("String input"));
//这里需要注意,服务端需要的是java.util.Date类型的参数,发布后经过xml客户端需要 javax.xml.datatype.XMLGregorianCalenda参数
//通过java.util.GregorianCalendar转换为需要的参数
//GregorianCalendar-〉XMLGregorianCalendar
GregorianCalendar nowGregorianCalendar =new GregorianCalendar();
try {
XMLGregorianCalendar xmlDatetime= DatatypeFactory.newInstance().newXMLGregorianCalendar(nowGregorianCalendar);
System.out.println(ms.myDateToString(xmlDatetime));
} catch (DatatypeConfigurationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}