一:所依赖的jar包:apache-cxf-2.7.10,可以再官网下载
二:编写web services的服务端:需要一个接口,叫做Hello,代码如下:在类名称前加入@WebService注释
package com;
import javax.jws.WebService;
@WebService
public interface Hello {
public String sayHello(String str);
}
三:编写接口实现类:包括传递的两种参数,一种是拼接的xml字符串
package com;
import java.util.HashMap;
import java.util.Map;<br>
@WebService(endpointInterface = "com.Hello")
public class HelloImpl implements Hello {
@Override
public String sayHello(String str) {
System.out.println("web services调用成功");
String result = createXml(str);
return result;
}
/**
* 根据传递的字符串生成对应的xml。
*
* @param 传递过来的参数name
* @return 返回xml的字符串
*/
public String createXml(String name) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version='1.0' encoding='UTF-8'?>");
sb.append("<Result>");
sb.append("<cinamaName>呵呵</cinamaName>");
sb.append("<director>" + name + "</director>");
sb.append("<introduce>我是说明</introduce>");
sb.append("<price>25</price>");
sb.append("</Result>");
return sb.toString();
}
}
四:编写web services的启动类,代码如下,运行,web services即可查询了:
public static void main(String[] args) {
try {
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("http://localhost:18080/aiplat/service/helloService?wsdl");
Object[] objs = client.invoke("sayHello","测试");
//接收结果
System.out.println(objs[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
Spring 配置:
<jaxws:server id="helloService" serviceClass="com.Hello" address="/helloService">
<jaxws:serviceBean>
<ref bean="helloImpl"/>
</jaxws:serviceBean>
</jaxws:server>
XML的解析:
/**
* 解析xml字符串
*
* @param str传递过来的xml字符串
*/
public static void parserXml(String str) {
try {
StringReader read = new StringReader(str);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);
NodeList movies = document.getChildNodes();
for (int i = 0; i < movies.getLength(); i++) {
Node employee = movies.item(i);
NodeList employeeInfo = employee.getChildNodes();
for (int j = 0; j < employeeInfo.getLength(); j++) {
Node node = employeeInfo.item(j);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if ("cinamaName".equals(node.getNodeName())) {
System.out.println( node.getTextContent());
} else if ("introduce".equals(node.getNodeName())) {
System.out.println( node.getTextContent());
} else if ("price".equals(node.getNodeName())) {
System.out.println( node.getTextContent());
} else if ("director".equals(node.getNodeName())) {
System.out.println(node.getTextContent());
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}