天天看點

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。