談到JSON,簡單的說就是一種數(shù)據(jù)交換格式。近年來,其在服務(wù)器之間交換數(shù)據(jù)的應(yīng)用越來越廣,相比XML其格式更簡單、編解碼更容易、擴(kuò)展性更好,所以深受開發(fā)人員的喜愛。
成都創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供攀枝花網(wǎng)站建設(shè)、攀枝花做網(wǎng)站、攀枝花網(wǎng)站設(shè)計(jì)、攀枝花網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、攀枝花企業(yè)網(wǎng)站模板建站服務(wù),10多年攀枝花做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
下面簡單的寫一下在項(xiàng)目中前后臺(tái)json傳值的一個(gè)小例子,供大家參考、查閱。
一:前臺(tái)傳后臺(tái)
1.前臺(tái)jsp頁面代碼:
在index中將實(shí)體對象(自己創(chuàng)建即可)插入list中,再將list集合轉(zhuǎn)化成json數(shù)組,利用post方式發(fā)送AJAX請求,將這個(gè)json數(shù)組發(fā)送至后臺(tái)(servlet),再在后臺(tái)進(jìn)行解析即可。
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"%>My first json page <% 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屆全運(yùn)會(huì)男單冠軍。"); 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年亞洲羽毛球錦標(biāo)賽亞軍。"); Listlist1 = new ArrayList (); list1.add(athlete1); list1.add(athlete2); JsonConfig jsonConfig = new JsonConfig();//解決date類型的傳輸問題 jsonConfig.registerJsonValueProcessor(Date.class , new JsonDateValueProcessor()); JSONArray jsonarray = JSONArray.fromObject(list1, jsonConfig); %>
2.后臺(tái)解析代碼:
后臺(tái)接受前臺(tái)傳來的json對象,解析插入數(shù)據(jù)庫中,且反給前臺(tái)一個(gè)是否成功的消息。具體插入數(shù)據(jù)庫的代碼自己編寫一個(gè)即可。
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表的頭數(shù)據(jù) String json2 = request.getParameter("athlete");//接收athlete表數(shù)據(jù) 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數(shù)組 for(int i=0;i"); out.println(" " + result + " "); out.println(""); out.close(); } else{ String result = "傳輸過程出錯(cuò),請重傳!"; out.println(""); out.println(" "); out.close(); } } catch (Exception e) { System.out .println("JsonServlet doPost(HttpServletRequest request, HttpServletResponse response) 報(bào)錯(cuò):" + e.getMessage()); } } public void init() throws ServletException { } }" + result + " "); out.println("
3.解決傳遞日期的一個(gè)工具類
若沒有這個(gè)工具類,date型數(shù)據(jù)會(huì)被轉(zhuǎn)化成json數(shù)組的格式,后臺(tái)解析起來會(huì)很復(fù)雜。
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; } }
二:后臺(tái)傳前臺(tái)
后臺(tái)以list和map兩種形式封裝json,前臺(tái)注意json數(shù)組和json對象解析時(shí)的差別即可。
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 );//轉(zhuǎn)化成json對象 //JSONObject jo=JSONObject.fromObject(m);//轉(zhuǎn)化Map對象 out.print(jsonArray2);//返給ajax請求 System.out.println(jsonArray2); //out.print(jo);//返給ajax請求 } }
2.showjson.jsp
利用Jquery、AJAX異步傳輸?shù)姆绞浇邮芎笈_(tái)的發(fā)送請求。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>