1、服务端
(1)接口:
package ws1; import java.util.List; import javax.jws.WebService; @WebService(name = "myService", portName = "myPort", serviceName = "myService", targetNamespace = "sun.com") public interface IMyService { int add(int a, int b); User addUser(User user); List<User> list(); boolean login(User user); }
package ws1; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class User { private Long id; private String name; private String sex; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; } }
package ws1; import java.util.ArrayList; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; @WebService(name = "myService", portName = "myPort", serviceName = "myService", targetNamespace = "sun.com") public class MyServiceImpl implements IMyService { private List<User> users = new ArrayList<User>(); @Override public @WebResult(name = "res") int add(@WebParam(name = "a") int a, @WebParam(name = "b") int b) { return a + b; } @WebMethod(exclude = false) @Override public @WebResult(name = "user") User addUser(@WebParam(name = "user") User user) { users.add(user); return user; } @WebMethod(exclude = false) @Override public @WebResult(name = "users") List<User> list() { return users; } @Override public @WebResult(name = "login") boolean login(@WebParam(name = "user") User user) { if (users.contains(user)) return true; return false; } }(3)发布类
package ws1; import javax.xml.ws.Endpoint; public class Publish { public static void main(String[] args) { String address = "http://localhost:8888/ws"; Object implementor = new MyServiceImpl(); Endpoint.publish(address, implementor); System.out.println("发布成功。。。"); } }2、客户端soap消息发送接收测试:
package ws1; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Random; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; 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.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.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class SOAPTest { private String ns = "sun.com"; private String wsdlLocation = "http://localhost:8888/ws?wsdl"; @Test public void testSOAPMsg() { try { // ***********************获取分发器*************************** URL wsdlDocumentLocation = new URL(wsdlLocation); QName serviceName = new QName(ns, "myService"); Service service = Service.create(wsdlDocumentLocation, serviceName); // MESSAGE 提供对整个协议消息的访问,而 PAYLOAD 只提供对协议消息负载的访问。 QName portName = new QName(ns, "myPort"); Dispatch<SOAPMessage> dispath = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE); // ***********************构建消息*************************** // 获取SOAPMessage对象实例 SOAPMessage message = MessageFactory.newInstance().createMessage(); // 获取SOAPPart SOAPPart part = message.getSOAPPart(); // 获取SOAPEnvelope SOAPEnvelope envelope = part.getEnvelope(); // 获取header // SOAPHeader header = envelope.getHeader(); // 获取body SOAPBody body = envelope.getBody(); /* * 手动构建消息 : * * SOAP Request Envelope: <soapenv:Envelope * xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" * xmlns:q0="targetNamespace->sun.com" * xmlns:xsd="http://www.w3.org/2001/XMLSchema" * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - * <soapenv:Body> - <q0:addAB> <a>4</a> <b>6</b> </q0:addAB> * </soapenv:Body> </soapenv:Envelope> * * SOAP Response Envelope: - <S:Envelope * xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> - <S:Body> - * <ns2:addABResponse xmlns:ns2="targetNamespace->sun.com"> * <res>10</res> </ns2:addABResponse> </S:Body> </S:Envelope> */ // QName格式:<sun:add xmlns:sun = "sun.com"> QName qname = new QName(ns, "add", "sun"); SOAPBodyElement sel = body.addBodyElement(qname); // body.addChildElement(qname); sel.addChildElement("a").setValue("4"); sel.addChildElement("b").setValue("6"); // 消息打印输出 message.writeTo(System.out); // ***********************发送消息、获取响应*************************** SOAPMessage respMsg = dispath.invoke(message); System.out.println(); respMsg.writeTo(System.out); // ***********************解析消息,得到结果*************************** Document dom = respMsg.getSOAPBody().extractContentAsDocument(); String res = dom.getElementsByTagName("res").item(0) .getTextContent(); System.out.println(); System.out.println("a + b = " + res); } catch (SOAPException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Test public void testAddUser() { try { URL wsdlDocumentLocation = new URL(wsdlLocation); QName serviceName = new QName(ns, "myService"); Service service = Service.create(wsdlDocumentLocation, serviceName); QName portName = new QName(ns, "myPort"); Dispatch<Source> dispath = service.createDispatch(portName, Source.class, Service.Mode.PAYLOAD); /* * 创建User并转换为xml格式 - * * SOAP Request Envelope: * * - <soapenv:Envelope * xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" * xmlns:q0="sun.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema" * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - * <soapenv:Body> - <q0:addUser> - <user> <age>1</age> <id>1</id> * <name>张三</name> <sex>男</sex> </user> </q0:addUser> * </soapenv:Body> </soapenv:Envelope> */ User user = new User(); user.setAge(new Random().nextInt(50)); user.setId(new Random().nextLong()); user.setName("name" + Math.abs(new Random().nextInt(50))); user.setSex(new Random().nextBoolean() ? "男" : "女"); JAXBContext jaxb = JAXBContext.newInstance(User.class); Marshaller marshaller = jaxb.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); StringWriter writer = new StringWriter(); marshaller.marshal(user, writer); System.out.println(writer.toString()); // 拼装xml数据 String payload = "<ss:addUser xmlns:ss='" + ns + "'>" + writer.toString() + "</ss:addUser>"; System.out.println(payload); StreamSource source = new StreamSource(new StringReader(payload)); Source respSource = dispath.invoke(source); Transformer transformer = TransformerFactory.newInstance() .newTransformer(); DOMResult dr = new DOMResult(); transformer.transform(respSource, dr); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//user", dr.getNode(), XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = (Node) nodeList.item(i); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); User u = (User) unmarshaller.unmarshal(node); System.out.println(u); } } catch (MalformedURLException 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(); } } }