xml 和javaBean

前端之家收集整理的这篇文章主要介绍了xml 和javaBean前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

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

具体代码如下:

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

Java代码
  1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.io.UnsupportedEncodingException;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.URL;
  10. import java.net.URLConnection;
  11. import java.net.URLEncoder;
  12. import java.net.URLDecoder;
  13. public class Client {
  14. private static final String POST = "http://localhost:8080/mobileCharge/charge/chargeAction!getMpay.action";
  15. public static void main(String[] args){
  16. sendXml();
  17. }
  18. public static String createXml() {
  19. String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<mpay>"
  20. + "<methodName>getMpay</methodName>" + "<params>" + "<param>"
  21. + "<type>1</type>" + "<terminalid>91300021</terminalid>"
  22. + "<money>100.00</money>" + "<csn>02570001</csn>"
  23. + "<password>1f3259007db02194cd134f18513dd00e</password>"
  24. + "</param>" + "</params>" + "</mpay>";
  25. return xml;
  26. }
  27. public static void sendXml(){
  28. try {
  29. URL url = new URL(POST);
  30. //根据URL地址打开一个连接
  31. URLConnection urlConnection = url.openConnection();
  32. HttpURLConnection httpUrlConnection = (HttpURLConnection)urlConnection;
  33. //允许输出
  34. httpUrlConnection.setDoOutput(true);
  35. //允许写入流
  36. httpUrlConnection.setDoInput(true);
  37. //post方式提交不可以使用缓存
  38. httpUrlConnection.setUseCaches(false);
  39. //请求类型
  40. httpUrlConnection.setRequestProperty("Content-Type","text/html");
  41. httpUrlConnection.setRequestMethod("POST");
  42. //设置连接、读取超时
  43. httpUrlConnection.setConnectTimeout(30000);
  44. httpUrlConnection.setReadTimeout(30000);
  45. httpUrlConnection.connect();
  46. //使用缓冲流将xml字符串发送给服务器
  47. BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream()));
  48. writer.write(URLEncoder.encode(createXml(),"UTF-8"));
  49. writer.flush();
  50. writer.close();
  51. writer = null;
  52. //关闭连接
  53. httpUrlConnection.disconnect();
  54. } catch (MalformedURLException e) {
  55. e.printStackTrace();
  56. } catch (UnsupportedEncodingException e) {
  57. e.printStackTrace();
  58. } catch (IOException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. }
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、服务端获取到此输入流后转换为字符串,这个很简单,贴出主要代码即可@H_502_12@

Java代码
  1. public String getXmlText(){
  2. //使用的是struts2 ,获取request很方便 O(∩_∩)O~
  3. HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
  4. String xmlText=null;
  5. try{
  6. //同样使用缓冲流
  7. BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
  8. StringBuffer sb = new StringBuffer();
  9. String lines;
  10. while((lines = reader.readLine())!=null){
  11. sb.append(lines);
  12. }
  13. //客户端使用了UTF-8编码,这里使用同样使用UTF-8解码
  14. xmlText = URLDecoder.decode(sb.toString(),"UTF-8");
  15. reader.close();
  16. reader = null;
  17. }catch(Exception e){
  18. e.printStackTrace();
  19. }
  20. return xmlText;
  21. }
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 的转换@H_502_12@

Java代码
  1. /**
  2. * 根据xml文件流对xmlModel赋值
  3. * @param xmlText
  4. * @param xmlModel
  5. * @L_502_8@
  6. */
  7. @SuppressWarnings("unchecked")
  8. public static synchronized Object parseXml4Bean(String xmlText,Object xmlModel){
  9. try {
  10. //解析字符串生成docment对象
  11. Document xmlDoc = DocumentHelper.parseText(xmlText);
  12. //获取根节点
  13. Element element = xmlDoc.getRootElement();
  14. List<Map<String,String>> propsList = new ArrayList<Map<String,String>>();
  15. //解析xml中的节点名称和节点值,详细见下面parseXml
  16. propsList = parseXml(element,propsList);
  17. if(propsList.size()==0){
  18. return null;
  19. }
  20. //获取Method对象数组
  21. Method[] methods = xmlModel.getClass().getDeclaredMethods();
  22. for(int i=0;i<propsList.size();i++){
  23. for(int j=0;j<methods.length;j++){
  24. Method m = methods[j];
  25. if(propsList.get(i).containsKey(m.getName())){
  26. try {
  27. //执行set方法,将xml中的textNode值赋予Model中
  28. m.invoke(xmlModel,new Object[]{propsList.get(i).get(m.getName())});
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }
  34. }
  35. } catch (DocumentException e) {
  36. e.printStackTrace();
  37. }
  38. return xmlModel;
  39. }
/**
	 * 根据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数组@H_502_12@

Java代码
  1. /**
  2. * 获取xml文件中叶结点名称和节点值
  3. * @param element
  4. * @param propsList
  5. * @return
  6. */
  7. @SuppressWarnings("unchecked")
  8. private static List<Map<String,String>> parseXml(Element element,List<Map<String,String>> propsList){
  9. if(element.isTextOnly()){
  10. HashMap<String,String> map = new HashMap<String,String>();
  11. String key = element.getName();
  12. key = METHOD_SET+key.substring(0,1).toUpperCase().concat(key.substring(1,key.length()));
  13. map.put(key,element.getTextTrim());
  14. propsList.add(map);
  15. }else{
  16. List<Element> tmpList = element.elements();
  17. for(Element e : tmpList){
  18. parseXml(e,propsList);
  19. }
  20. }
  21. return propsList;
  22. }
/**
	 * 获取xml文件中叶结点名称和节点值
	 * @param element
	 * @param propsList
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private static 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@H_502_12@

Java代码
  1. package com.eptok.business.charge;
  2. public class ChargeXmlModel {
  3. private String methodName;
  4. private String type;
  5. private String terminalid;
  6. private String money;
  7. private String csn;
  8. private String password;
  9. public String getMethodName() {
  10. return methodName;
  11. }
  12. public void setMethodName(String methodName) {
  13. this.methodName = methodName;
  14. }
  15. public String getType() {
  16. return type;
  17. }
  18. public void setType(String type) {
  19. this.type = type;
  20. }
  21. public String getTerminalid() {
  22. return terminalid;
  23. }
  24. public void setTerminalid(String terminalid) {
  25. this.terminalid = terminalid;
  26. }
  27. public String getMoney() {
  28. return money;
  29. }
  30. public void setMoney(String money) {
  31. this.money = money;
  32. }
  33. public String getCsn() {
  34. return csn;
  35. }
  36. public void setCsn(String csn) {
  37. this.csn = csn;
  38. }
  39. public String getPassword() {
  40. return password;
  41. }
  42. public void setPassword(String password) {
  43. this.password = password;
  44. }
  45. }
  46. /////////////////////
    1. package main;
    2. import java.io.File;
    3. import java.io.FileNotFoundException;
    4. import java.io.FileOutputStream;
    5. import java.io.FileReader;
    6. import javax.xml.bind.JAXBContext;
    7. import javax.xml.bind.JAXBException;
    8. import javax.xml.bind.Marshaller;
    9. import javax.xml.bind.Unmarshaller;
    10. import demo.model.Person;
    11. public class Main {
    12. /**
    13. * @param args
    14. * @throws JAXBException
    15. * @throws FileNotFoundException
    16. */
    17. public static void main(String[] args) throws JAXBException,FileNotFoundException {
    18. JAXBContext ctx=JAXBContext.newInstance(Person.class);
    19. toXML(ctx);
    20. fromXML(ctx);
    21. }
    22. public static void toXML(JAXBContext ctx) throws JAXBException,FileNotFoundException{
    23. Marshaller ms=ctx.createMarshaller();
    24. FileOutputStream fo=new FileOutputStream(new File("src/Person.xml"));
    25. Person p=new Person();
    26. //"Jack","12";
    27. p.age="ss";
    28. ms.marshal(p,fo);
    29. }
    30. public static void fromXML(JAXBContext ctx) throws FileNotFoundException,JAXBException{
    31. FileReader fo=new FileReader(new File("src/Person.xml"));
    32. Unmarshaller ums= ctx.createUnmarshaller();
    33. Person p=(Person) ums.unmarshal(fo);
    34. System.out.println(p.username);
    35. }
    36. }
    package main;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    
    import demo.model.Person;
    
    public class Main {
    
    	/**
    	 * @param args
    	 * @throws JAXBException 
    	 * @throws FileNotFoundException 
    	 */
    	public static void main(String[] args) throws JAXBException,FileNotFoundException {
    		JAXBContext ctx=JAXBContext.newInstance(Person.class);
    		toXML(ctx);
    		fromXML(ctx);
    		
    	}
    	public static void toXML(JAXBContext ctx) throws JAXBException,FileNotFoundException{
    		Marshaller ms=ctx.createMarshaller();
    		FileOutputStream fo=new FileOutputStream(new File("src/Person.xml"));
    		Person p=new Person();
    		//"Jack","12";
    		p.age="ss";
    		ms.marshal(p,fo);
    	}
    	public static void fromXML(JAXBContext ctx) throws FileNotFoundException,JAXBException{
    		FileReader fo=new FileReader(new File("src/Person.xml"));
    		Unmarshaller ums= ctx.createUnmarshaller();
    		Person p=(Person) ums.unmarshal(fo);
    		System.out.println(p.username);
    	}
    
    }


    Java代码
    1. package demo.model;
    2. import javax.xml.bind.annotation.XmlAttribute;
    3. import javax.xml.bind.annotation.XmlRootElement;
    4. @XmlRootElement
    5. public class Person {
    6. public Person() {
    7. super();
    8. }
    9. public Person(String username,String age) {
    10. super();
    11. this.username = username;
    12. this.age = age;
    13. }
    14. @XmlAttribute
    15. public String username;
    16. public String age;
    17. }

猜你在找的XML相关文章