首页 > 代码库 > webservice初级
webservice初级
在学习webservice的时候,经常将ns和url花了好久时间才理解过来,这里备份下!
首先定义接口:
@WebService
public interface IService
{
@WebResult(name = "login")
public User login(@WebParam(name = "username") String username,
@WebParam(name = "password") String password);
}
创建实现类:
@WebService(endpointInterface = "com.cml.soap.IService[这里是实现接口的全路径]", name = "myname")
public class ServiceImpl implements IService
{
@Override
@WebResult(name = "login")
public User login(@WebParam(name = "username") String username,
@WebParam(name = "password") String password)
{
System.out.println("进来登录");
return new User("恭喜你登录成功!", 1);
}
}
发布服务:
String address = "http://localhost:8888/cml";
Endpoint.publish(address, new ServiceImpl());
在浏览器上输入http://localhost:8888/cm?wsdl
创建soap消息:
public void sendSoap() throws Exception
{
String ns = "http://soap.cml.com/";
QName name = new QName(ns, "ServiceImplService");
String url = "http://localhost:8888/cml?wsdl";
// 使用的是url进行服务的创建
Service service = Service.create(new URL(url), name);
Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,
"mynamePort"), SOAPMessage.class, Service.Mode.MESSAGE);
SOAPMessage msg = MessageFactory.newInstance().createMessage();
SOAPEnvelope ele = msg.getSOAPPart().getEnvelope();
SOAPBody body = ele.getBody();
QName name2 = new QName(ns, "login", "tns");// <tns:login xmlns=""
SOAPBodyElement element = body.addBodyElement(name2);
element.addChildElement("username").setValue("1111");
element.addChildElement("password").setValue("222");
msg.writeTo(System.out);
SOAPMessage response = dispatch.invoke(msg);
System.out.println("\n服务器响应回来");
response.writeTo(System.out);
// 获取返回信息的文档对象
Document document = response.getSOAPPart().getEnvelope().getBody()
.extractContentAsDocument();
System.out.println();
System.out.println(document.getElementsByTagName("login").item(0)
.getTextContent());
}