您好,登錄后才能下訂單哦!
談到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 = "servlet/JsonServlet"; 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>
2.后臺解析代碼:
后臺接受前臺傳來的json對象,解析插入數據庫中,且反給前臺一個是否成功的消息。具體插入數據庫的代碼自己編寫一個即可。
JsonServlet.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 JsonServlet extends HttpServlet { public JsonServlet() { 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("JsonServlet 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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。