码迷,mamicode.com
首页 > Web开发 > 详细

webservice初级

时间:2014-05-26 03:41:56      阅读:302      评论:0      收藏:0      [点我收藏+]

标签: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());

}

bubuko.com,布布扣






webservice初级,布布扣,bubuko.com

webservice初级

标签:webservice

原文地址:http://blog.csdn.net/cml_blog/article/details/26616923

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!