一:项目需求,前端有一个页面,页面中可以手动输入一些参数数据,通过点击前端的按钮,使输入的数据保存到后台生成的.xml文件中
二:我在前端使用的是easyui的propertygrid,这个能通过data-options中的URL:
'/task1/com/guodiantong/servlet/JsonToJspServlet.action'这个地址对应后台的servlet,要求在对应的servlet中必须有json格式的字符串输出:
String ss=javaToGson.javaToString(list);//这个里面用到的是com.google.gson.Gson这个jar包,这个jar包是实现json格式数据到字符串或javabean转换很好的包
response.setContentType("application/json");
response.getWriter().write(ss);
效果图如下:
三:项目架构:自己写的一个httpservlet
四:上代码:
1):先看从前台到后台写入xml文件代码:
前端的代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="easyui.css"> <link rel="stylesheet" type="text/css" href="demo.css"> <script type="text/javascript" src="jquery.min.js"></script> <script type="text/javascript" src="jquery.easyui.min.js"></script> </head> <body> <div style="margin:20px 0;"></div> <table id="pg" class="easyui-propertygrid" style="width:300px" data-options=" url: '/task1/com/guodiantong/servlet/JsonToJspServlet.action', method: 'get', showGroup: true, scrollbarSize: 0, columns: mycolumns "> </table> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="transferData()" >向XML文件中传递数值</a> <br> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="transferDataToJsp()" >从XML文件中向前台传递数值</a> <script type="text/javascript"> function transferData(){ var opt=$('#pg').propertygrid('getData'); //console.log(opt); var row=opt.rows; //console.log(row); var as=[]; var temp=[]; for(var i=0;i<row.length;i++){ var a=row[i].name; temp.push('{"name":'+'"' +a+'"'+ ','); // console.log(a); var b=row[i].value; if(i==row.length-1){ temp.push('"value":'+ '"'+b+'"'); temp.push('}'); }else{ temp.push('"value":'+ '"'+b+'"'); temp.push('}'+'_'); } //console.log(b); } as.push(temp.join("")); console.log(as); jQuery.ajax({ url:"/task1/com/guodiantong/servlet/xmlServlet.do", type:"POST", data:{aa:as} }) } function transferDataToJsp(){ jQuery.ajax({ url:"/task1/com/guodiantong/servlet/JsonToJspServlet.action", type:"POST", success:function(data){ alert(1); }, error:function(XMLHttpRequest, textStatus, errorThrown){ console.log(errorThrown); } }) $('#pg').propertygrid('reload'); } </script> </body> </html>
接受前台数据用到的javabean:
package com.guodiantong.domain; public class PropertyGrid { public String name; public String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public PropertyGrid(String name, String value) { this.name = name; this.value = value; } public PropertyGrid() { } @Override public String toString() { return "PropertyGrid [name=" + name + ", value=" + value + "]"; } }
1.1从前台到后台写入xml文件的过程涉及到的代码:servlet代码
package com.guodiantong.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.guodiantong.domain.PropertyGrid; import com.guodiantong.logicmethod.GsonToJava; import com.guodiantong.xmlparse.CreateXmlNode; public class xmlServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath="/propertygrid.xml"; String[] obj= request.getParameterValues("aa[]"); String as[]=obj[0].split("_"); System.out.println(obj[0]); System.out.println(as.length); List<PropertyGrid> list=new ArrayList<PropertyGrid>(); GsonToJava gsonToJava=new GsonToJava(); list=gsonToJava.springToJava(as); for(PropertyGrid pro:list){ System.out.println(pro); System.out.println(pro.getValue()); } System.out.println(request.getContextPath()); CreateXmlNode createXmlNode=new CreateXmlNode(); try { createXmlNode.createXmlWithNode(list, filePath); } catch (Exception e) { e.printStackTrace(); } //System.out.println(request.getRealPath(null)); } }
servlet中涉及到的方法代码:
package com.guodiantong.logicmethod; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.guodiantong.domain.PropertyGrid; public class GsonToJava { private void GsonToJava() { } public List<PropertyGrid> springToJava(String[] s){ Gson gson=new Gson(); List<PropertyGrid> list=new ArrayList<PropertyGrid>(); PropertyGrid propertyGrid=new PropertyGrid(); for(int i=0;i<s.length;i++){ propertyGrid=gson.fromJson(s[i], PropertyGrid.class); list.add(propertyGrid); } return list; } }
写入xml文件数据的方法:注意到,在这个代码中我是把前台的数据写到了e盘下的.Person.xml文件里了
package com.guodiantong.xmlparse; import java.io.FileOutputStream; import java.io.StringWriter; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.guodiantong.domain.PropertyGrid; public class CreateXmlNode { public CreateXmlNode() { // TODO Auto-generated constructor stub } public boolean createXmlWithNode(List<PropertyGrid> list,String filePath) throws Exception{ Document document=DocumentHelper.createDocument(); Element root=document.addElement("parameters"); for(int i=0;i<list.size();i++){ Element param=root.addElement(list.get(i).getName()); param.addText(list.get(i).getValue()); } StringWriter stringWriter=new StringWriter(); OutputFormat xmlFormat=new OutputFormat(); xmlFormat.setEncoding("UTF-8"); xmlFormat.setNewlines(true); xmlFormat.setIndent(true); xmlFormat.setIndent(" "); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("e:/Person.xml"),xmlFormat); //写入文件 xmlWriter.write(document); //关闭 xmlWriter.close(); // 输出xml System.out.println(stringWriter.toString()); return true; } }
1.2从前台从后台读取数据的过程代码:前提是我已经有一个Person.xml文件,然后把这些数据读到我前端的表格里面对应的字段去:
servlet代码:
package com.guodiantong.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.DocumentException; import com.guodiantong.domain.PropertyGrid; import com.guodiantong.logicmethod.JavaToGson; import com.guodiantong.xmlparse.ReadXmlNode; public class JsonToJspServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //System.out.println("hello dopost"); String fileName="e:/Person.xml"; ReadXmlNode readXmlNode=new ReadXmlNode(); JavaToGson javaToGson=new JavaToGson(); List<PropertyGrid> list=new ArrayList<PropertyGrid>(); try { list=readXmlNode.xmlToList(fileName); System.out.println(list); String ss=javaToGson.javaToString(list); int length=javaToGson.stringLength(list); System.out.println(length); System.out.println(ss); File writeFile=new File("E:/2015/prj/task1/WebContent/propertygrid_data1.vm"); FileOutputStream fw=new FileOutputStream(writeFile); String propertygrid_vm="{"+"\"total\":"+length+",\"rows\":" + ss + "}"; fw.write(propertygrid_vm.getBytes()); fw.flush(); fw.close(); response.setContentType("application/json"); response.getWriter().write(ss); } catch (DocumentException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
涉及到的方法:
package com.guodiantong.logicmethod; import java.util.List; import com.google.gson.Gson; import com.guodiantong.domain.PropertyGrid; public class JavaToGson { public JavaToGson() { // TODO Auto-generated constructor stub } public String javaToString(List<PropertyGrid> list){ Gson gson=new Gson(); return gson.toJson(list); /*String ss=""; for(int i=0;i<list.size();i++){ String temp; temp=gson.toJson(list.get(i)); if(i==list.size()-1){ ss=ss+temp; }else{ ss=ss+temp+","; } } return ss;*/ } public int stringLength(List<PropertyGrid> list){ Gson gson=new Gson(); String ss=""; for(int i=0;i<list.size();i++){ String temp; temp=gson.toJson(list.get(i)); if(i==list.size()-1){ ss=ss+temp; }else{ ss=ss+temp+"_"; } } String ssArray[]=ss.split("_"); int length=ssArray.length; return length; } }
package com.guodiantong.xmlparse; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.guodiantong.domain.PropertyGrid; public class ReadXmlNode { public ReadXmlNode() { // TODO Auto-generated constructor stub } public List<PropertyGrid> xmlToList(String fileName) throws DocumentException{ List<PropertyGrid> list=new ArrayList<PropertyGrid>(); System.out.println("进入了xmlToList方法"); SAXReader reader=new SAXReader(); Document doc=reader.read(fileName); //System.out.println(doc); Element root=doc.getRootElement(); for ( Iterator i = root.elementIterator(); i.hasNext(); ) { PropertyGrid propertyGrid=new PropertyGrid(); Element element = (Element) i.next(); propertyGrid.setName(element.getName()); propertyGrid.setValue(element.getText()); // // do something // System.out.println(element.getName()); // System.out.println(element.getText()); list.add(propertyGrid); } return list; } }
后台的xml文件:
<?xml version="1.0" encoding="UTF-8"?> <parameters> <Name1>Bill Smith</Name1> <Address1></Address1> <zst>27</zst> <Age>40</Age> <Birthday>01/02/2012</Birthday> <SSN23>123-456-7890</SSN23> <hhh>2334</hhh> <Email>bill@gmail.com</Email> <FrequentBuyer>false</FrequentBuyer> <xiaopenghui>nb</xiaopenghui> <lx1>nb</lx1> <abc1>hhh</abc1> <tx1>456</tx1> <hello2>world</hello2> <ag>lll</ag> <qq>1032077316</qq> </parameters>