鉴于CXF框架的web service学习,传递xml,json并解析,容易上手

所依赖的jar包:apache-cxf-2.7.10,可以再官网下载,还有json.rar的对应包,联系是一个java 项目

一:下载对应Jar,可以在官网下载,或是到我资源下载,里面jar都齐全了,将apache-cxf-2.7.10下面的Lib中的jar加入项目中

二:.编写web services的服务端:需要一个接口,叫做Hello,代码如下:在类名称前加入@WebService注释

package com;

import javax.jws.WebService;

import net.sf.json.JSONObject;

@WebService
public interface Hello {

	public String sayHello(String str);

	public JSONObject sayJson(String str);

	public String sayJsonStr(String str);

}

三:编写接口实现类:包括传递的两种参数,一种是拼接的xml字符串,一种是json的对象

package com;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class HelloImpl implements Hello {

	@Override
	public String sayHello(String str) {
		System.out.println("web services调用成功");
		String result = createXml(str);
		return result;
	}

	public static void main(String[] args) throws Exception {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("name", "liqineng");
		String[] likes = new String[] { "music", "movie", "study" };
		jsonObj.put("hobby", likes);
		Map<String, String> ingredients = new HashMap<String, String>();
		ingredients.put("age", "23");
		ingredients.put("EnglishName", "spider man");
		ingredients.put("sex", "boy");
		ingredients.put("love", "tangwei");
		jsonObj.put("message", ingredients);
		System.out.println(jsonObj);

	}

	/**
	 * 创建JsonOBject对象
	 * 
	 * @param 客户端传递的参数Name
	 * @return 返回jsonObject对象
	 */
	public JSONObject createJsonObject(String name) {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("name", "liqineng");
		String[] likes = new String[] { "music", "movie", "study" };
		jsonObj.put("hobby", likes);
		Map<String, String> ingredients = new HashMap<String, String>();
		ingredients.put("age", "23");
		ingredients.put("EnglishName", "spider man");
		ingredients.put("sex", "boy");
		ingredients.put("love", "tangwei");
		jsonObj.put("message", ingredients);
		return jsonObj;
	}

	/**
	 * 根据传递的字符串生成对应的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>一部好莱坞大片,3D观影,不错!!!</introduce>");
		sb.append("<price>25</price>");
		sb.append("</Result>");
		return sb.toString();
	}

	@Override
	public JSONObject sayJson(String str) {

		return createJsonObject(str);
	}

	@Override
	public String sayJsonStr(String str) {
		return createJsonObject(str).toString();
	}

}

四:编写web services的启动类,代码如下,运行,web services即可查询了:

package com;

import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

public class MainServer {

	public static void main(String[] args) {
		JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
		factory.setAddress("http://192.168.10.197:8080/cxf");
		factory.setServiceClass(HelloImpl.class);
		Server server = factory.create();
		server.start();
	}
}

然后可以输入:http://192.168.10.197:8080/cxf?wsdl 在浏览器上进行查看,你可以可以下载一个soapUi进行专业的测试


第五:编写Webservice的客户端:如果不在同一个项目中的话,同样也需要下载对应的jar包文件,

需要创建一个接口,接口也是方法,注意:方法也需要添加@WebService注释,代码如下:


package com;

import javax.jws.WebService;

import net.sf.json.JSONObject;

@WebService
public interface Hello {
	public String sayHello(String str);

	public JSONObject sayJson(String str);

	public String sayJsonStr(String str);

}



主的接收和解析类:包括xml解析,json的解析:

package com;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSONObject;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * 客户端调用类。
 * 
 * 
 */
public class Client {
	public static void main(String[] args) {
		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(Hello.class);
		factory.setAddress("http://192.168.10.197:8080/cxf?wsdl");
		Hello hello = (Hello) factory.create();
		String xml = hello.sayHello("zhangsan");
		// JSONObject obj = hello.sayJson("liqineng");
		// parserXml(xml);
		String str = hello.sayJsonStr("liqineng");
		ParseJsonStr(str);
		// System.out.println(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());
		}
	}

	public static void ParseJsonObject(JSONObject obj) {

		System.out.println(obj);
		String name = obj.getString("name");
	}

	/**
	 * 解析json字符串
	 * 
	 * @param str传递过来的json字符串
	 */
	public static void ParseJsonStr(String str) {

		JSONObject obj = JSONObject.fromObject(str);
		System.out.println(obj);
		String name = obj.getString("name");
		String hobby = obj.getString("hobby");
		JSONObject message = obj.getJSONObject("message");
		String love = message.getString("love");
		String sex = message.getString("sex");
		int age = message.getInt("age");
		String englishName = message.getString("EnglishName");
		System.out.println(hobby);
		System.out.println(name + ">>" + hobby + ">>" + love + ">>" + sex
				+ ">>" + age + ">>" + englishName);
	}
}



这样,一个java的Webservice完成了,并进行的现在比较流行的xml,json的解析,希望大家看了之后对自己有所帮助,如有疑问,留言讨论



鉴于CXF框架的web service学习,传递xml,json并解析,容易上手,布布扣,bubuko.com

鉴于CXF框架的web service学习,传递xml,json并解析,容易上手

上一篇:在 RequireJS 之前预先装载某些代码块


下一篇:be a geek-从零开始学编程:无处不在的css 1