1. 创建一个接口
package com.dolo.services;
import javax.jws.WebService;
@WebService//注解
public interface MyServices {
@WebResult(name="addRusult")
public int add(@WebParam(name="a")int a, @WebParam(name="b")int b);
@WebResult(name="minusRusult")
public int minus(@WebParam(name="a")int a, @WebParam(name="b")int b);
}
@WebResult(name="修改wsdl页面方法名")
@WebParam(name="修改wsdl页面参数名")
2. 实现这个接口
package com.dolo.services;
import javax.jws.WebService;
@WebService(endpointInterface="com.dolo.services.MyServices")//注解
public class MyServicesImpl implements MyServices {
public int add(int a, int b) {
System.out.println(a+"+"+b+"="+(a+b));
return a+b;
}
public int minus(int a, snt b) {
System.out.println(a+"-"+b+"="+(a-b));
return a-b;
}
}
3. 服务开启
public static void main(String[] args) {
// TODO Auto-generated method stub
String address = "http://localhost:5555/my";
Endpoint.publish(address, new MyServicesImpl());
}
4. 页面访问:http://localhost:5555/my?wsdl
5. 调用测试
package com.dolo.services;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class MyServiceUse {
/**
* @param args
* QName("命名空间()targetNamespace","服务名(name)")
*/
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:5555/my?wsdl");
QName qname = new QName("http://services.dolo.com/","MyServicesImplService");
Service service = Service.create(url,qname);
MyServices ms = service.getPort(MyServices.class);
System.out.println(ms.add(12, 55));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
6. 通过wsdl生成本地类(wsimport的使用)
1.在D盘创建一个文件夹
1.cmd—d:--wsimport—(-d)指明要生成的目录)verbose(查看生成的详细信息)-p(指明生成的包 –keep(生成后是否保存源代码)
包结构默认为命名空间反过来
控制台:wsimport -d:/webservice/01/ -keep -erbose http://localhost:5555/my?wsdl
2.将生成的文件导入项目
3.生成的类中有一个以ImplService结尾的类,有一个getXXXPort的方法,可以获得原接口,之后即可使用它调用原接口方法
MyServicesImplService service = new MyServicesImplService();
MyServices impl = service.getMyServicesImplPort();
impl.mins(55, 22);
//或者MyServicesImplService(url,qname);
/**
URL url = new URL("http://localhost:5555/my?wsdl");
QName qname = new QName("http://services.dolo.com/","MyServicesImplService");
MyServicesImplService service = new MyServicesImplService(url,qname);
*/
异常解决:增加注解
javax.xml.ws.WebServiceException: Unable to create JAXBContext
at com.sun.xml.internal.ws.model.AbstractSEIModelImpl.createJAXBContext(AbstractSEIModelImpl.java:153)
@WebService(name = "InsurancePolicyService", targetNamespace = "http://service.weixin.eservice.focus.cmc.cigna.com/")
@XmlSeeAlso({
ObjectFactory.class
})
@SOAPBinding(style = SOAPBinding.Style.RPC)