java学习

java学习

 

soap消息的分析和消息的创建和传递和处理



@WebService
public interface IMyService {
 @WebResult(name="addResult")
 public int add(@WebParam(name="a")int a,@WebParam(name="b")int b);
 
 @WebResult(name="user")
 public User addUser(@WebParam(name="user")User user);
 
 @WebResult(name="user")
 public User login(@WebParam(name="username")String username,
       @WebParam(name="password")String password)throws UserException;
 
 @WebResult(name="user")
 public List<User> list(@WebParam(header=true,name="authInfo")String authInfo);
}

@XmlRootElement
public class User {
 private int id;
 private String username;
 private String nickname;
 private String password;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getNickname() {
  return nickname;
 }
 public void setNickname(String nickname) {
  this.nickname = nickname;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public User(int id, String username, String nickname, String password) {
  super();
  this.id = id;
  this.username = username;
  this.nickname = nickname;
  this.password = password;
 }
 public User() {
  super();
 }
 
 
 
}

public class MyServer {

 public static void main(String[] args) {
  Endpoint.publish("http://localhost:8989/ms", new MyServiceImpl());
 }

}



--

 

@WebService(endpointInterface="org.soap.service.IMyService")
@HandlerChain(file="handler-chain.xml")
public class MyServiceImpl implements IMyService {
 private static List<User> users = new ArrayList<User>();
 
 public MyServiceImpl() {
  users.add(new User(1,"admin","","111111"));
 }

 @Override
 public int add(int a, int b) {
  System.out.println("a+b="+(a+b));
  return a+b;
 }

 @Override
 public User addUser(User user) {
  users.add(user);
  return user;
 }

 @Override
 public User login(String username, String password) throws UserException{
  for(User user:users) {
   if(username.equals(user.getUsername())&&password.equals(user.getPassword()))
    return user;
  }
  throw new UserException("");
 }

 @Override
 public List<User> list(String authInfo) {
  System.out.println(authInfo);
  return users;
 }

}

public class TestSoap {
 
 private static String ns = "http://service.soap.org/";
 private static String wsdlUrl = "http://localhost:8989/ms?wsdl";
       
        public static void main(String[] args){
            TestSoap.test03();
        }

 @Test
 public static void test01() {
  try {
   //1�������创建消息工厂���
   MessageFactory factory = MessageFactory.newInstance();
   //2����根据消息工厂创建SoapMessage
   SOAPMessage message = factory.createMessage();
   //3�����创建SOAPPart
   SOAPPart part = message.getSOAPPart();
   //4��获取SOAPENvelope
   SOAPEnvelope envelope = part.getEnvelope();
   //5��可以通过SoapEnvelope有效的获取相应的Body和Header等信息
   SOAPBody body = envelope.getBody();
   //6���根据Qname创建相应的节点(QName就是一个带有命名空间的节点)���������ռ��)
   QName qname = new QName("http://java.zttc.edu.cn/webservice",
     "add","ns");//<ns:add xmlns="http://java.zttc.edu.cn/webservice"/>
   //�如果使用以下方式进行设置,会见<>转换为&lt;和&gt
   //body.addBodyElement(qname).setValue("<a>1</a><b>2</b>");
   SOAPBodyElement ele = body.addBodyElement(qname);
   ele.addChildElement("a").setValue("22");
   ele.addChildElement("b").setValue("33");
   //打印消息信息
   message.writeTo(System.out);
  } catch (SOAPException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 @Test//基于soap的消息传递
 public static void test02() {
  try {
   //1���创建服务(Service)
   URL url = new URL(wsdlUrl);
   QName sname = new QName(ns,"MyServiceImplService");
   Service service = Service.create(url,sname);
   
   //2����创建Dispatch
   Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
      SOAPMessage.class, Service.Mode.MESSAGE);
   
   //3����创建SOAPMessage
   SOAPMessage msg = MessageFactory.newInstance().createMessage();
   SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
   SOAPBody body = envelope.getBody();
   
   //4���创建QName来指定消息中传递数据����
   QName ename = new QName(ns,"add","nn");//<nn:add xmlns="xx"/>
   SOAPBodyElement ele = body.addBodyElement(ename);
   ele.addChildElement("a").setValue("22");
   ele.addChildElement("b").setValue("33");
   msg.writeTo(System.out);
   System.out.println("\n invoking.....");
   
   
   //5�通过Dispatch传递消息,会返回响应消息
   SOAPMessage response = dispatch.invoke(msg);
   response.writeTo(System.out);
   System.out.println("\n----------------------------------------");
   
   //��将响应的消息转换为dom对象��
   Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
   String str = doc.getElementsByTagName("addResult").item(0).getTextContent();
   System.out.println(str);
  } catch (SOAPException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 @Test
 public static void test03() {
  try {
   //1�����创建服务(Service)
   URL url = new URL(wsdlUrl);
   QName sname = new QName(ns,"MyServiceImplService");
   Service service = Service.create(url,sname);
   
   //2���创建Dispatch(通过源数据的方式传递)
   Dispatch<Source> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
      Source.class, Service.Mode.PAYLOAD);
   //3���根据用户对象创建相应的xml
   User user = new User(3,"zs","张三","11111");
                        //编排user对象
   JAXBContext ctx = JAXBContext.newInstance(User.class);
   Marshaller mar = ctx.createMarshaller();
                        //不会再创建xml的头信息
   mar.setProperty(Marshaller.JAXB_FRAGMENT, true);
   StringWriter writer= new StringWriter();
   mar.marshal(user, writer);
   System.out.println("writer====="+writer);
   //4、封装相应的part addUser
   String payload = "<xs:addUser xmlns:xs=\""+ns+"\">"+writer.toString()+"</xs:addUser>";
   System.out.println("payload====="+payload);
   StreamSource rs = new StreamSource(new StringReader(payload));
   
   //5�通过dispatch传递payload
   Source response = (Source)dispatch.invoke(rs);
   
   //6�将Source转化为DOM进行操作,使用Transform对象转换
   Transformer tran = TransformerFactory.newInstance().newTransformer();
   DOMResult result = new DOMResult();
   tran.transform(response, result);
   
   //7���处理相应信息(通过xpath处理)
   XPath xpath = XPathFactory.newInstance().newXPath();
   NodeList nl = (NodeList)xpath.evaluate("//user", result.getNode(),XPathConstants.NODESET);
   User ru = (User)ctx.createUnmarshaller().unmarshal(nl.item(0));
   System.out.println(ru.getNickname());
  } catch (IOException e) {
   e.printStackTrace();
  } catch (JAXBException e) {
   e.printStackTrace();
  } catch (TransformerConfigurationException e) {
   e.printStackTrace();
  } catch (TransformerFactoryConfigurationError e) {
   e.printStackTrace();
  } catch (TransformerException e) {
   e.printStackTrace();
  } catch (XPathExpressionException e) {
   e.printStackTrace();
  }
 }

posted on 2013-08-13 10:04 杨军威 阅读(1314) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜