java实现简单的webservice方式

 更新时间:2017年05月12日 14:17:56   作者:梦想如歌!   我要评论
这篇文章主要为大家详细介绍了java实现简单的webservice方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java实现webservice方式的具体代码,供大家参考,具体内容如下

经过测试 jdk1.6.10以下会出现bug 建议使用10以上版本

1、定义接口

package org.enson.chan;
 
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
 
@WebService
@SOAPBinding(style=SOAPBinding.Style.RPC)
public interface IMyService {
 public int add(int a , int b);
 
 public int max(int a , int b);
}

2、实现接口

package org.enson.chan;
import javax.jws.WebService;

@WebService(endpointInterface="org.enson.chan.IMyService")
public class MyServiceImpl implements IMyService {

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

 public int max(int a, int b) {
 System.out.println("a与b比较大小,取大值"+((a>b)?a:b));
 return (a>b)?a:b;
 }

}

3、定义服务

package org.enson.chan;
 
import javax.xml.ws.Endpoint;
 
public class MyServer {
 
 public static void main(String[] args) {
 String address = "http://localhost:8090/ns";
 Endpoint.publish(address, new MyServiceImpl());
 }
}

4、测试服务

package org.enson.chan;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class TestClient {

 public static void main(String[] args) {
 try {
  URL url = new URL("http://localhost:8090/ns?wsdl");
  QName sname = new QName("http://chan.enson.org/", "MyServiceImplService");
  //创建服务
  Service service = Service.create(url,sname);
  //实现接口
  IMyService ms = service.getPort(IMyService.class);
  System.out.println(ms.add(12,33));
  //以上服务有问题,依然依赖于IMyServie接口
 } catch (MalformedURLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 }

}

5、TestSoap

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPFaultException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.junit.Test;
import org.soap.service.User;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class TestSoap {
 
 private String ns = "http://service.soap.org/";
 private String wsdlUrl = "http://localhost:8989/ms?wsdl";

 @Test
 public void test01() {
 try {

  MessageFactory factory = MessageFactory.newInstance();
  
  SOAPMessage message = factory.createMessage();

  SOAPPart part = message.getSOAPPart();

  SOAPEnvelope envelope = part.getEnvelope();

  SOAPBody body = envelope.getBody();

  QName qname = new QName("http://java.zttc.edu.cn/webservice", 
   "add","ns");//<ns:add xmlns="http://java.zttc.edu.cn/webservice"/>

  //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
 public void test02() {
 try {
  URL url = new URL(wsdlUrl);
  QName sname = new QName(ns,"MyServiceImplService");
  Service service = Service.create(url,sname);
  
  Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
   SOAPMessage.class, Service.Mode.MESSAGE);
  
  SOAPMessage msg = MessageFactory.newInstance().createMessage();
  SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
  SOAPBody body = envelope.getBody();
  
  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.....");
  
  
  SOAPMessage response = dispatch.invoke(msg);
  response.writeTo(System.out);
  System.out.println();
  
  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 void test03() {
 try {
  URL url = new URL(wsdlUrl);
  QName sname = new QName(ns,"MyServiceImplService");
  Service service = Service.create(url,sname);
  
  Dispatch<Source> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
   Source.class, Service.Mode.PAYLOAD);
  
  User user = new User(3,"zs","张三","11111");
  JAXBContext ctx = JAXBContext.newInstance(User.class);
  Marshaller mar = ctx.createMarshaller();
  mar.setProperty(Marshaller.JAXB_FRAGMENT, true);
  StringWriter writer= new StringWriter();
  mar.marshal(user, writer);
  
  String payload = "<nn:addUser xmlns:nn=\""+ns+"\">"+writer.toString()+"</nn:addUser>";
  System.out.println(payload);
  StreamSource rs = new StreamSource(new StringReader(payload));
  
  Source response = (Source)dispatch.invoke(rs);
  
  Transformer tran = TransformerFactory.newInstance().newTransformer();
  DOMResult result = new DOMResult();
  tran.transform(response, result);
  
  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();
 }
 }
 
 @Test
 public void test04() {
 try {
  URL url = new URL(wsdlUrl);
  QName sname = new QName(ns,"MyServiceImplService");
  Service service = Service.create(url,sname);
  
  Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
   SOAPMessage.class, Service.Mode.MESSAGE);
  
  SOAPMessage msg = MessageFactory.newInstance().createMessage();
  SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
  SOAPBody body = envelope.getBody();
  
  SOAPHeader header = envelope.getHeader();
  if(header==null) header = envelope.addHeader();
  QName hname = new QName(ns,"authInfo","nn");
  header.addHeaderElement(hname).setValue("aabbccdd");
  
  QName ename = new QName(ns,"list","nn");//<nn:add xmlns="xx"/>
  body.addBodyElement(ename);
  msg.writeTo(System.out);
  System.out.println("\n invoking.....");
  
  
  SOAPMessage response = dispatch.invoke(msg);
  response.writeTo(System.out);
  System.out.println();
  
  Document doc = response.getSOAPBody().extractContentAsDocument();
  NodeList nl = doc.getElementsByTagName("user");
  JAXBContext ctx = JAXBContext.newInstance(User.class);
  for(int i=0;i<nl.getLength();i++) {
  Node n = nl.item(i);
  User u = (User)ctx.createUnmarshaller().unmarshal(n);
  System.out.println(u.getNickname());
  }
 } catch (SOAPException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (JAXBException e) {
  e.printStackTrace();
 }
 }
 
 @Test
 public void test05() {
 try {
  URL url = new URL(wsdlUrl);
  QName sname = new QName(ns,"MyServiceImplService");
  Service service = Service.create(url,sname);
  
  Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns,"MyServiceImplPort"),
   SOAPMessage.class, Service.Mode.MESSAGE);
  
  SOAPMessage msg = MessageFactory.newInstance().createMessage();
  SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
  SOAPBody body = envelope.getBody();
  
  QName ename = new QName(ns,"login","nn");//<nn:add xmlns="xx"/>
  SOAPBodyElement ele = body.addBodyElement(ename);
  ele.addChildElement("username").setValue("ss");
  ele.addChildElement("password").setValue("dd");
  msg.writeTo(System.out);
  System.out.println("\n invoking.....");
  
  
  SOAPMessage response = dispatch.invoke(msg);
  response.writeTo(System.out);
  System.out.println();
  
 } catch(SOAPFaultException e){
  System.out.println(e.getMessage());
 } catch (SOAPException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } 
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java并发之传统线程同步通信技术代码详解

    Java并发之传统线程同步通信技术代码详解

    这篇文章主要介绍了Java并发之传统线程同步通信技术代码详解,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • Java通过匿名类来实现回调函数实例总结

    Java通过匿名类来实现回调函数实例总结

    这篇文章主要介绍了Java通过匿名类来实现回调函数的例子,回调函数就是一种函数签名(若干个输入参数、一个输出参数)的规范,java虽不存在函数声明,但是java可以用接口来强制规范。具体操作步骤大家可查看下文的详细讲解,感兴趣的小伙伴们可以参考一下。
    2017-08-08
  • MyBatis 使用权威指南

    MyBatis 使用权威指南

    MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集,本文给大家介绍MyBatis 使用指南,一起看看吧
    2017-03-03
  • Java编程实现帕斯卡三角形代码示例

    Java编程实现帕斯卡三角形代码示例

    这篇文章主要介绍了Java编程实现帕斯卡三角形代码示例,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • Springboot+redis+Interceptor+自定义annotation实现接口自动幂等

    Springboot+redis+Interceptor+自定义annotation实现接口自动幂等

    本篇文章给大家介绍了使用springboot和拦截器、redis来优雅的实现接口幂等,对于幂等在实际的开发过程中是十分重要的,因为一个接口可能会被无数的客户端调用,如何保证其不影响后台的业务处理,如何保证其只影响数据一次是非常重要的,感兴趣的朋友跟随小编一起看看吧
    2019-07-07
  • Springboot整合Shiro之加盐MD5加密的方法

    Springboot整合Shiro之加盐MD5加密的方法

    这篇文章主要介绍了Springboot整合Shiro之加盐MD5加密的方法,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-12-12
  • 详解Spring配置事务的五种方式

    详解Spring配置事务的五种方式

    这篇文章主要为大家详细介绍了Spring配置事务的五种方式,感兴趣的小伙伴们可以参考一下
    2016-06-06
  • Java语言实现简单FTP软件 FTP软件远程窗口实现(6)

    Java语言实现简单FTP软件 FTP软件远程窗口实现(6)

    这篇文章主要为大家详细介绍了Java语言实现简单FTP软件,FTP软件远程窗口的实现方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-03-03
  • java中使用双向链表实现贪吃蛇程序源码分享

    java中使用双向链表实现贪吃蛇程序源码分享

    这篇文章主要介绍了java中使用双向链表实现贪吃蛇程序源码分享,本文直接给出了实现代码,需要的朋友可以参考下
    2015-03-03
  • 详解Android系统中的root权限获得原理

    详解Android系统中的root权限获得原理

    这篇文章主要介绍了详解Android系统中的Root权限获得原理,安卓基于Linux,所以原理也相当于Linux中的root用户,需要的朋友可以参考下
    2015-08-08

最新评论