談到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>