xml文件流与javabean之间的通用转换(上)

最近在做通讯方面的一些东西,移动端与服务器之间的通讯采用HttpUrlConnection以xml文件流的方式进行通讯。xml文件解析后,通常要给对应的数据模型(javabean)赋值,从而进行一些列的验证,入库,日志操作等。

 

1、通过HttpUrlConnection获取输入流,解码后生成xml文件字符串

2、使用dom4j解析此字符串生成Document对象

3、对Document对象递归遍历收集节点名称和节点值,并根据节点名称拼接set方法,用以和javabean反射后得到的set方法做匹配

 

具体代码如下:

 

1、模拟客户端发送xml数据流至服务器 Client.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.URLDecoder;

public class Client {
	
	private static final String POST = "http://localhost:8080/mobileCharge/charge/chargeAction!getMpay.action";
	
	public static void main(String[] args){
		sendXml();
	}
	
	public static String createXml() {
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<mpay>"
				+ "<methodName>getMpay</methodName>" + "<params>" + "<param>"
				+ "<type>1</type>" + "<terminalid>91300021</terminalid>"
				+ "<money>100.00</money>" + "<csn>02570001</csn>"
				+ "<password>1f3259007db02194cd134f18513dd00e</password>"
				+ "</param>" + "</params>" + "</mpay>";
		return xml;
	}
	
	
	public static void sendXml(){
		try {
			URL url = new URL(POST);
			//根据Url地址打开一个连接
			URLConnection urlConnection = url.openConnection();
			HttpURLConnection httpUrlConnection = (HttpURLConnection)urlConnection;
			//允许输出流
			httpUrlConnection.setDoOutput(true);
			//允许写入流
			httpUrlConnection.setDoInput(true);
			//post方式提交不可以使用缓存
			httpUrlConnection.setUseCaches(false);
			//请求类型
			httpUrlConnection.setRequestProperty("Content-Type", "text/html");
			httpUrlConnection.setRequestMethod("POST");
			//设置连接、读取超时
			httpUrlConnection.setConnectTimeout(30000);
			httpUrlConnection.setReadTimeout(30000);
			httpUrlConnection.connect();
			//使用缓冲流将xml字符串发送给服务器
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream()));
			writer.write(URLEncoder.encode(createXml(),"UTF-8"));
			writer.flush();
			writer.close();
			writer = null;
			//关闭连接
			httpUrlConnection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

2、服务端获取到此输入流后转换为字符串,这个很简单,贴出主要代码即可

public String getXmlText(){
		//使用的是struts2 ,获取request很方便 O(∩_∩)O~
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
		String xmlText=null;
		try{
			//同样使用缓冲流
			BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String lines;
			while((lines = reader.readLine())!=null){
				sb.append(lines);
			}
			//客户端使用了UTF-8编码,这里使用同样使用UTF-8解码
			xmlText = URLDecoder.decode(sb.toString(),"UTF-8");
			reader.close();
			reader = null;
		}catch(Exception e){
			e.printStackTrace();
		}
		return xmlText;
		
	}

 

 一下就是xmlText与javabean之间的转换了,今天只写了上部分 xml - javabean  改天再写下部分 javabean - xml

 

3、xmlText -  javabean 的转换

 

/**
	 * 根据xml文件流对xmlModel赋值
	 * @param xmlText
	 * @param xmlModel
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static synchronized Object parseXml4Bean(String xmlText,Object xmlModel){
		try {
			//解析字符串生成docment对象
			Document xmlDoc = DocumentHelper.parseText(xmlText);
			//获取根节点
			Element element = xmlDoc.getRootElement();
			List<Map<String,String>> propsList = new ArrayList<Map<String,String>>();
			//解析xml中的节点名称和节点值,详细见下面parseXml
			propsList = parseXml(element, propsList);
			if(propsList.size()==0){
				return null;
			}
			//获取Method对象数组
			Method[] methods = xmlModel.getClass().getDeclaredMethods();
			for(int i=0;i<propsList.size();i++){
				for(int j=0;j<methods.length;j++){
					Method m = methods[j];
					if(propsList.get(i).containsKey(m.getName())){
						try {
							//执行set方法,将xml中的textNode值赋予Model中
							m.invoke(xmlModel, new Object[]{propsList.get(i).get(m.getName())});
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return xmlModel;
	}

 

 4、子方法 ,用以解析xml,拼接set方法匹配与Method数组

/**
	 * 获取xml文件中叶结点名称和节点值
	 * @param element
	 * @param propsList
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static List<Map<String,String>> parseXml(Element element,List<Map<String,String>> propsList){
		if(element.isTextOnly()){
			HashMap<String,String> map = new HashMap<String,String>();
			String key = element.getName();
			key = METHOD_SET+key.substring(0,1).toUpperCase().concat(key.substring(1,key.length()));
			map.put(key,element.getTextTrim());
			propsList.add(map);
		}else{
			List<Element> tmpList = element.elements();
			for(Element e : tmpList){
				parseXml(e, propsList);
			}
		}
		return propsList;
	}

 

 

 5、java bean

package com.eptok.business.charge;

public class ChargeXmlModel {
	private String methodName;
	private String type;
	private String terminalid;
	private String money;
	private String csn;
	private String password;

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getTerminalid() {
		return terminalid;
	}

	public void setTerminalid(String terminalid) {
		this.terminalid = terminalid;
	}

	public String getMoney() {
		return money;
	}

	public void setMoney(String money) {
		this.money = money;
	}

	public String getCsn() {
		return csn;
	}

	public void setCsn(String csn) {
		this.csn = csn;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

 

6、测试调用   。。。。

 附件中有dom4j的jar ,可以下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值