json前后台传值
谈到JSON,简单的说就是一种数据交换格式。近年来,其在服务器之间交换数据的应用越来越广,相比XML其格式更简单、编解码更容易、扩展性更好,所以深受开发人员的喜爱。
下面简单的写一下在项目中前后台json传值的一个小例子,供大家参考、查阅。
一:前台传后台
1.前台jsp页面代码:
在index中将实体对象(自己创建即可)插入list中,再将list集合转化成json数组,利用post方式发送AJAX请求,将这个json数组发送至后台(servlet),再在后台进行解析即可。
index.jsp
<%@ page language="java" import="java.util.Date,com.badminton.utils.JsonDateValueProcessor,java.text.SimpleDateFormat,java.util.List,net.sf.json.JSONArray,net.sf.json.JSONObject,net.sf.json.JsonConfig,java.util.ArrayList,com.badminton.entity.Athlete,net.sf.json.JSONObject" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My first json page</title> <% SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); Athlete athlete1 = new Athlete(); athlete1.setAthlete_id(1003); athlete1.setAthlete_name("林丹"); athlete1.setAthlete_sex("男"); Date athlete_age1 = format1.parse("1983-10-14");//是java.util.date athlete1.setAthlete_age(athlete_age1); athlete1.setCoach_id(101); athlete1.setEvent_id(1); athlete1.setService_status("1"); athlete1.setExperience("2013年第12届全运会男单冠军。"); Athlete athlete2 = new Athlete();//记录2 athlete2.setAthlete_id(1004); athlete2.setAthlete_name("鲍春来"); athlete2.setAthlete_sex("男"); Date athlete_age2 = format1.parse("1988-10-14"); athlete2.setAthlete_age(athlete_age2); athlete2.setCoach_id(101); athlete2.setEvent_id(1); athlete2.setService_status("1"); athlete2.setExperience("2011年亚洲羽毛球锦标赛亚军。"); List<Athlete> list1 = new ArrayList<Athlete>(); list1.add(athlete1); list1.add(athlete2); JsonConfig jsonConfig = new JsonConfig();//解决date类型的传输问题 jsonConfig.registerJsonValueProcessor(Date.class , new JsonDateValueProcessor()); JSONArray jsonarray = JSONArray.fromObject(list1, jsonConfig); %> <script type="text/javascript" src="js/json2.js"></script> <script type="text/javascript"> var xmlHttp; function createXmlHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } //回调 function handleStateChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { parseResults(); } } } //将后台返回的数据显示在层serverResponse中 function parseResults() { var result=xmlHttp.responseXML.getElementsByTagName("result")[0].firstChild.data; alert(result); } function doJSON() { var athletehead={athlete_id:1,tablename:"athlete"}; var myobj=eval(athletehead); var str1=JSON.stringify(myobj);//str1以后可用来识别数据库中的表 var str2=‘<%=jsonarray%>‘; var url = "http://localhost:8080/com.badminton.servlet/JsonServer"; createXmlHttpRequest(); xmlHttp.open("POST", url, true); xmlHttp.onreadystatechange = handleStateChange;//回调 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;text/xml;charset=utf-8"); //text/xml;charset=utf-8:解决汉字封装json问题 xmlHttp.send("athletehead="+str1+"&athlete="+str2);//传送了两个对象 } </script> </head> <body> <form id="form1"> <table> <tr> <td align="center"><input type="button" name="submit" value="提交" onClick="doJSON()"></td> </tr> </table> </form> </body> </html>
后台接受前台传来的json对象,解析插入数据库中,且反给前台一个是否成功的消息。具体插入数据库的代码自己编写一个即可。
JsonServer.java
package com.badminton.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.badminton.app.AthleteAction; import net.sf.json.JSONObject; import net.sf.json.JSONArray; public class JsonServer extends HttpServlet { public JsonServer() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); AthleteAction athleteaction=new AthleteAction(); try { String json1 = request.getParameter("athletehead");//接收athlete表的头数据 String json2 = request.getParameter("athlete");//接收athlete表数据 json1 = java.net.URLDecoder.decode(json1,"UTF-8"); json2 = java.net.URLDecoder.decode(json2, "UTF-8"); if ((json1 != "") && (json2 != "")) { //System.out.println("json1:"+json1); JSONObject jsonObject1 =JSONObject.fromObject(json1);//生成json对象 JSONArray jsonArray2 = JSONArray.fromObject(json2);//生成JSON数组 for(int i=0;i<jsonArray2.size();i++){ JSONObject resultObj = jsonArray2.optJSONObject(i);//根据JSONArray生成JSONObject int athlete_id=resultObj.getInt("athlete_id"); String athlete_name=resultObj.getString("athlete_name"); String athlete_sex=resultObj.getString("athlete_sex"); String age=resultObj.getString("athlete_age"); Date athlete_age = Date.valueOf(age);//转换成java.sql.Date //System.out.println(athlete_age); int coach_id=resultObj.getInt("coach_id"); int event_id=resultObj.getInt("event_id"); System.out.println(athlete_name); String service_status=resultObj.getString("service_status"); String experience=resultObj.getString("experience"); athleteaction.athleteAdd(athlete_id,athlete_name,athlete_sex,athlete_age,coach_id,event_id,service_status,experience);//对数据库进行操作,具体代码未附 } String result = "数据上传成功!"; out.println("<response>"); out.println("<result>" + result + "</result>"); out.println("</response>"); out.close(); } else{ String result = "传输过程出错,请重传!"; out.println("<response>"); out.println("<result>" + result + "</result>"); out.println("</response>"); out.close(); } } catch (Exception e) { System.out .println("JsonServer doPost(HttpServletRequest request, HttpServletResponse response) 报错:" + e.getMessage()); } } public void init() throws ServletException { } }
3.解决传递日期的一个工具类
若没有这个工具类,date型数据会被转化成json数组的格式,后台解析起来会很复杂。
JsonDateValueProcessor.java
package com.badminton.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; public class JsonDateValueProcessor implements JsonValueProcessor{ /** * datePattern */ private String datePattern = "yyyy-MM-dd"; /** * JsonDateValueProcessor */ public JsonDateValueProcessor() { super(); } /** * @param format */ public JsonDateValueProcessor(String format) { super(); this.datePattern = format; } /** * @param value * @param jsonConfig * @return Object */ public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value); } /** * @param key * @param value * @param jsonConfig * @return Object */ public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) { return process(value); } /** * process * @param value * @return */ private Object process(Object value) { try { if (value instanceof Date) { SimpleDateFormat sdf = new SimpleDateFormat(datePattern, Locale.UK); return sdf.format((Date) value); } return value == null ? "" : value.toString(); } catch (Exception e) { return ""; } } /** * @return the datePattern */ public String getDatePattern() { return datePattern; } /** * @param pDatePattern the datePattern to set */ public void setDatePattern(String pDatePattern) { datePattern = pDatePattern; } }
二:后台传前台
后台以list和map两种形式封装json,前台注意json数组和json对象解析时的差别即可。
1.TestJson.java
package com.badminton.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class TestJson extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String str= request.getParameter("name");//得到ajax传递过来的paramater System.out.println(str); PrintWriter out = response.getWriter(); List list = new ArrayList();//传递List //Map m=new HashMap();//传递Map User u1=new User(); u1.setUsername("zah"); u1.setPassword("123"); User u2=new User(); u2.setUsername("ztf"); u2.setPassword("456"); list.add(u1); //添加User对象 list.add(u2); //添加User对象 //m.put("u1", u1); //m.put("u2", u2); JSONArray jsonArray2 = JSONArray.fromObject( list );//转化成json对象 //JSONObject jo=JSONObject.fromObject(m);//转化Map对象 out.print(jsonArray2);//返给ajax请求 System.out.println(jsonArray2); //out.print(jo);//返给ajax请求 } }
2.showjson.jsp
利用Jquery、AJAX异步传输的方式接受后台的发送请求。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript"> function test(){ $.ajax({ type:"POST", //请求方式 url:"servlet/TestJson",//请求路径 cache: false, data:"name=zah", /传参 dataType: ‘json‘,//返回值类型 success:function(json){ alert(json[1].username+" "+ json[1].password);//弹出返回过来的List对象 } }); } </script> </head> <body> <input type="button" name="b" value="测试" </body> </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。