最近工作中碰到一个工作需求,需要两个系统进行数据交互,把一个系统中的相关
数据传递到另外一个系统中去。
阐明一下当时的一个环境:
1)公司有两个系统,一个是订单处理系统,一个是库存系统;订单处理系统放在公司机房内部,而库存系统放在公司总部机房,不在同一
局域网。
2)订单系统获取到相关库存数据,包括产品数据、库位、数量等,依据订单的相关信息,进行产品比对,发货等等操作
由于
工作经验有限,在此之前没有碰到过类似的情况。接到任务后,我第一时间想到的是把这些数据用OutputStream给输出到浏览器中,这样既可以在浏览器中查看,也可以获取到这些信息进行
解析,这样对项目的结构调整也不大。后来由于项目慢慢的要做些调整和优化之后,利用这个时机就把这个需求通过Web
Service给实现了。孰优孰劣按我的经验暂时无法判断,不过个人还是比较喜欢WebService。
第一种方法:把信息写入OutputStream中去
1.以
XML的方式进行输出
1)DAO查询数据
class="java"> // 分页查询
public List<Barcodegoods> queryBarcodegoodsByPage(String page,
String pageSize) {
Integer current;//当前页码
Integer pageCount;//每页条数
if (page != null && !"".equals(page)) {
current = Integer.valueOf(page);
} else {
current = currentpage;
}
if (pageSize != null && !"".equals(pageSize)) {
pageCount = Integer.valueOf(pageSize);
} else {
pageCount = pagesize;
}
StringBuffer buffer = new StringBuffer();
buffer.append("select * from barcodegoods ");
buffer.append("limit ");
buffer.append((current - 1) * pageCount);
buffer.append(",");
buffer.append(pageCount);
String sql = buffer.toString();
List<Barcodegoods> bgs = new ArrayList<Barcodegoods>();
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
pstmt = conn.prepareStatement(sql);
res = pstmt.executeQuery();
Barcodegoods bg = null;
while (res.next()) {
bg = new Barcodegoods();
bg.setBarcode(res.getString("barcode"));
bg.setColorid(res.getString("colorid"));
bg.setGoods_no(res.getString("goods_no"));
bg.setSize(res.getString("size"));
bgs.add(bg);
}
} catch (SQLException e) {
e.printStackTrace();
}
return bgs;
}
2)输出XML格式信息
public void createXml(List<Barcodegoods> list, PrintWriter out) {
Document document = DocumentHelper.createDocument();
Element stocks = document.addElement("stocks");// 创建根节点
Barcodegoods bean = null;
for (int i = 0; i < list.size(); i++) {
bean = list.get(i);
Element stock = stocks.addElement("stock");
Element barcode = stock.addElement("barcode");
Element goodsNo = stock.addElement("goods_no");
Element colorid = stock.addElement("colorid");
Element size = stock.addElement("size");
barcode.setText(bean.getBarcode());
goodsNo.setText(bean.getGoods_no());
colorid.setText(bean.getColorid());
size.setText(bean.getSize());
}
// 输出
try {
OutputFormat format = new OutputFormat(" ", true);
format.setEncoding("gb2312");
// 输出创建的xml文档
XMLWriter output = new XMLWriter(out, format);
output.write(document);
out.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
利用了Dom4j当中的XMLWriter类包装PrintWriter进行输出
3)编写请求响应的
Servlet,利用Servlet进行响应输出XML内容
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();//获取PrintWriter
String current = "1";//当前页码
String pageSize = "20";//每页总数
String page = request.getParameter("page");
if(page!=null){
String parray[] = page.split(",");
current = parray[0];
pageSize = parray[1];
}
String checkCode = request.getParameter("checkcode");
if("passing".equals(checkCode)){
response.setContentType("text/xml;charset=gb2312");//内容类型和字符集
response.setHeader("Cache-Control", "no-cache");//响应头
XmlApi api = new XmlApi();
List<Barcodegoods> bgs = api.queryBarcodegoods(current, pageSize);
api.createXml(bgs, out);
}else{
out.print("check failed!!!");
return;
}
out.flush();
out.close();
}
可以命令请求时需要带参数,并且参数验证通过后才给与返回,不然就不接受请求!
浏览器的请求地址为:
http://localhost:8083/webdemo/XmlApiServlet?checkcode=passing&page=1,5结果为:
<stocks>
<stock>
<barcode>FL009620010110</barcode>
<goods_no>FL00962</goods_no>
<colorid>0010</colorid>
<size>110</size>
</stock>
<stock>
<barcode>B622180202200</barcode>
<goods_no>B622180</goods_no>
<colorid>2022</colorid>
<size>00</size>
</stock>
<stock>
<barcode>B622180107100</barcode>
<goods_no>B622180</goods_no>
<colorid>1071</colorid>
<size>00</size>
</stock>
<stock>
<barcode>BB13150203900</barcode>
<goods_no>BB13150</goods_no>
<colorid>2039</colorid>
<size>00</size>
</stock>
<stock>
<barcode>BB13150222000</barcode>
<goods_no>BB13150</goods_no>
<colorid>2220</colorid>
<size>00</size>
</stock>
</stocks>
结果正确可以正常显示库存信息
4)用JAVA的方式来获取此库存信息
public static void main(String[] args) throws Exception {
URL url = new URL( "http://localhost:8083/webdemo/XmlApiServlet?checkcode=passing");
URLConnection conn = url.openConnection();
conn.setDoInput(true);//默认也是true。如果设置成false,这无法读取InputStream
InputStream in = conn.getInputStream();
SAXReader reader = new SAXReader();
List<List<String>> list = new ArrayList<List<String>>();
List<String> list1 = null;
Document document = reader.read(in);//通过IO流产生Document对象
Element stocks = document.getRootElement();//获取根元素
for (Iterator i = stocks.elementIterator(); i.hasNext();) {//遍历Stock节点
list1 = new ArrayList();//一个Stcok中的所有属性
Element stock = (Element) i.next();// 获得每个stock
for (Iterator j = stock.elementIterator(); j.hasNext();) {//遍历Stock节点下的属性节点
Element node = (Element) j.next();// 获得每个stock中的属性
list1.add(node.getText());// 把属性存放到List1中
}
list.add(list1);//存放所有的stock的信息
}
//存放数据
List<Barcodegoods> bars = new ArrayList<Barcodegoods>();
Barcodegoods goods = null;
for(List<String> data : list){
goods = new Barcodegoods();//new出barcodegoods对象,为它赋值
goods.setBarcode(data.get(0));
goods.setGoods_no(data.get(1));
goods.setColorid(data.get(2));
goods.setSize(data.get(3));
bars.add(goods);
}
//输出产品的条形码
for(Barcodegoods b :bars){
System.out.println(b.getBarcode());
}
}
通过获取连接中的InputStream,来解析XML。
2.以
JSON的方式输出
1)产生
JSON的类方法
//构造JSON字符串
public String makeJsonString(List<Barcodegoods> list) {
if (list != null && list.size() > 0) {
List<JSONObject> objects = new ArrayList<JSONObject>();
Map<String, JSONObject> omap = new HashMap<String, JSONObject>();
Map<String,String> map = null;//JSON对象每个属性
for(Barcodegoods bg : list){
map = new HashMap<String, String>();
map.put("barcode", bg.getBarcode());
map.put("goodsno", bg.getGoods_no());
map.put("colorid", bg.getColorid());
map.put("size", bg.getSize());
JSONObject jobj = JSONObject.fromObject(map);//将每个MAP转换成key-value的JSON对象
objects.add(jobj);//存放所有的JSON对象
}
Map<String,Object> olists = new HashMap<String, Object>();//
olists.put("barcodegoods", objects.toArray());//把Barcodegoods当做key,把objects当做value
olists.put("status", "success");//添加status属性
JSONObject obj = JSONObject.fromObject(olists);//转化成JSON
//return obj.toString();
omap.put("message", obj);
return omap.toString();
}else{
return "failed";
}
}
JSON数据的构成可以依据需求进行构造,只要符合业务需求的数据构造就可以了
2)输出JSON的Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String page = request.getParameter("page");
String current = "1";// 当前页
String pageSize = "10";// 每页总数
if (page != null) {// 判断是否自定义分页
String[] pages = page.split(",");
if (pages.length == 2) {//两个参数缺一不可
current = pages[0];
pageSize = pages[1];
}
}
String checkcode = request.getParameter("checkcode");// 验证参数
if ("passing".equals(checkcode)) {// 判断验证参数
JsonApi api = new JsonApi();
List<Barcodegoods> bgs = api.queryBarcodegoods(current, pageSize);// 查询数据
String jsonString = api.makeJsonString(bgs);// 构造JSON字符串
out.print(jsonString);// 输出JSON字符串
} else {
out.print("check failed");
}
}
可以命令请求时需要带参数,并且参数验证通过后才给与返回,不然就不接受请求!
浏览器的请求地址为:
http://localhost:8083/webdemo/JsonApiServlet?checkcode=passing&page=1,5结果为:
{message={"barcodegoods":[{"goodsno":"FL00962","colorid":"0010","barcode":"FL009620010110","size":"110"},{"goodsno":"B622180","colorid":"2022","barcode":"B622180202200","size":"00"},{"goodsno":"B622180","colorid":"1071","barcode":"B622180107100","size":"00"},{"goodsno":"BB13150","colorid":"2039","barcode":"BB13150203900","size":"00"},{"goodsno":"BB13150","colorid":"2220","barcode":"BB13150222000","size":"00"}],"status":"success"}}
3)JAVA解析输出的数据
public static void main(String[] args) throws Exception {
URL url = new URL( "http://localhost:8083/webdemo/JsonApiServlet?checkcode=passing"); URLConnection conn = url.openConnection();
conn.setDoInput(true);// 默认也是true。如果设置成false,这无法读取InputStream
InputStream in = conn.getInputStream();
byte[] b = new byte[1024];
int length = 0;
StringBuffer buffer = new StringBuffer();
while((length=in.read(b))>0){
buffer.append(new String(b,0,length));//读取JSON字符串
}
JSONObject json = JSONObject.fromObject(buffer.toString());//转换为JSON对象
JSONObject message = json.getJSONObject("message");//获取Message属性
JSONArray barcodegoods = message.getJSONArray("barcodegoods");//获取barcodegoods集合属性
List<Barcodegoods> bgs = new ArrayList<Barcodegoods>();
Barcodegoods bg = null;
for(int i=0;i<barcodegoods.size();i++){//遍历集合
bg = new Barcodegoods();
JSONObject goods = barcodegoods.getJSONObject(i);//遍历集合中的json对象
bg.setBarcode(goods.getString("barcode"));//获取值,并且赋值
bg.setColorid(goods.getString("colorid"));
bg.setGoods_no(goods.getString("goodsno"));
bg.setSize(goods.getString("size"));
bgs.add(bg);
}
for(Barcodegoods bs : bgs){
System.out.println(bs.getBarcode());
}
}
这个是当时的做法,后来由于其他原因,就改成了WebService的方法进行传递