天天看点

Maven搭建SpringWebService(2)-服务端service方法改写

接着昨天的继续。

昨天写的服务端类中的方法参数具体到了传入的每个参数。如果我们的设计的WS服务端有很多输入参数,我觉得这样需要包装一下参数。

今天利用空闲时间看了一下@XPathParam注解的源码,Spring在源码的注释中写道:

<ul> 
<li>
{@code boolean}, or {@link * Boolean}
</li> <li>{@code double}, or {@link Double}</li> <li>{@link String}</li> <li>{@link
 * org.w3c.dom.Node}</li> <li>{@link org.w3c.dom.NodeList}</li> </ul>
           

看到上面的注释,我觉得使用Node对象应该封装传来的参数,于是改写昨天的服务端类的方法,源码如下:

@PayloadRoot(localPart = "AddUserRequest", namespace = NAMESPACE_URI)
	@Namespace(prefix = "ws", uri = NAMESPACE_URI)
	@ResponsePayload
	public Element addUser(@XPathParam("//ws:User") Node userNode) throws Exception {
		
		NodeList list = userNode.getChildNodes();
		for(int i = 0 ; i < list.getLength() ; i++){
			Node node = list.item(i);
			if(node.hasChildNodes()){
				System.out.println(true);
				System.out.println(node.getNodeName() +" " + node.getTextContent() + " " + <span style="background-color: rgb(255, 102, 102);">node.getNodeValue()</span>);
			} else {
				System.out.println(false);
			}
			
		}

		Element response = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder().newDocument()
				.createElementNS(NAMESPACE_URI, "AddUserResponse");
		response.setTextContent("1");
		return response;
	}
           

这里要说一下:node.getNodeValue()没有值的,如果要获取参数中的值,需要使用node.getTextContent()来获取。

为什么呢?google大神告诉我:XML中,只有属性、备注、文本,这几种节点才有nodeValue。