webservice 第三讲 SOAP

1.创建接口
package org.soap.service;

import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@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);
}

2.创建实现类
package org.soap.service;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

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

}

3.开启服务
package org.soap.service;

import javax.xml.ws.Endpoint;

public class MyServer {

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

}

4.SOAP 消息的建立
    private String ns = "http://service.soap.org/";
    private String wsdlUrl = "http://localhost:8889/ns?wsdl";

	@Test
	public 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.soap.third.cn/webservice", 
					"add","ns");//<ns:add xmlns="http://java.soap.third.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();
		}
	}

5.SOAP显示打印消息
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><ns:add xmlns:ns="http://java.soap.third.cn/webservice"><a>22</a><b>33</b></ns:add></SOAP-ENV:Body></SOAP-ENV:Envelope>


6.SOAP消息的创建与服务器端进行交互MESSAGE方式
@Test
	public 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();
			
			//将响应的消息转换为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();
		}
	}
	

7.显示打印信息
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><nn:add xmlns:nn="http://service.soap.org/"><a>22</a><b>33</b></nn:add></SOAP-ENV:Body></SOAP-ENV:Envelope>
 invoking.....
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header/><S:Body><ns2:addResponse xmlns:ns2="http://service.soap.org/"><addResult>55</addResult></ns2:addResponse></S:Body></S:Envelope>
55

8.SOAP消息的创建与服务器端进行交互PAYLOAD方式
@Test
	public 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","wr","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);
			
			//4、封装相应的part addUser
			String payload = "<nn:addUser xmlns:nn=\""+ns+"\">"+writer.toString()+"</nn:addUser>";
			System.out.println(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();
		}
	}

9.SOAP消息的创建与服务器端进行交互MESSAGE方式,增加head信息
@Test
	public void test04() {
		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();
			
			//3.2、处理header信息
			SOAPHeader header = envelope.getHeader();
			if(header==null) header = envelope.addHeader();
			QName hname = new QName(ns,"authInfo","nn");
			header.addHeaderElement(hname).setValue("wxh");
			
			//4、创建QName来指定消息中传递数据
			QName ename = new QName(ns,"list","nn");//<nn:add xmlns="xx"/>
			body.addBodyElement(ename);
			msg.writeTo(System.out);
			System.out.println("\n invoking.....");
			
			
			//5、通过Dispatch传递消息,会返回响应消息
			SOAPMessage response = dispatch.invoke(msg);
			response.writeTo(System.out);
			System.out.println();
			
			//将响应的消息转换为dom对象
			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();
		}
	}

10SOAP消息的创建与服务器端进行交互MESSAGE方式,异常信息
@Test
	public void test05() {
		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,"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.....");
			
			
			//5、通过Dispatch传递消息,会返回响应消息
			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();
		} 
	}

你可能感兴趣的:(SOAP)