Spring接受前端傳數據的幾種格式


 

時間就是金錢,時間就是生命,時間是不可再生資源

 

背景介紹:

 在一開發者活動社區,

有人提問如何向后台傳送數組和對象嵌套列表的數據格式,我一想這不就是老生常談的話題嗎,

於是給他解決了后,在想,為什么不把以前的解決方式寫到網了呢,天下無稀罕事,都是重復性的多。新出來的開發者也會遇到同樣的問題(就是說老程序們曾經出現的問題又在新開發者身上重新演了一遍,只是換了人而已)

,我們把以前解決問題的方式方法寫到網上,這樣新的開發者們就不用再花時間研究了,可以直接套,提升效率,節省時間。

前端向后端傳數據,無非就三種(可能會有變體或組合):普通字符串或整數,數組型實體類型, 對象嵌套型

1.  前台向后台傳送普通字符串或數字或布爾,就不說了,沒什么好講的

2,. 前台向后端傳數組格式或變體的數據。

2.1   像List<String>或List<Integer>,有三種方式,看個人喜歡或公司規范自行選擇

        2.1.1 第一種方式,前端代碼:

var systemType= new Array(); 
systemType.push(0);  
systemType.push(1);  
systemType.push(2); 
$.ajax({ 
  type: "POST", 
  url: "<%=basePath%>/tools/add", 
  dataType: 'json', 
  data: {"title":"python開發", systemType":systemType}, 
  success: function(data){ 
    … 
  }, 
  error: function(res){ 
    … 
  } 
}); 

 

后端代碼:

/**
     * 資料
     * @param title(標題)
     * @param systemType(類型)
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @LoginRequired
    @CrossOrigin
    public JSONObject add(@CurrentUser User user, 
            @RequestParam(value = "title", required = true, defaultValue = "") String title,
            @RequestParam("systemType[]",defaultValue = "[]") List<Integer>  systemType) {
//直接獲取前台傳來的值
...
}

 

 2.1.2  第二種方式,前台通過JSON.stringify轉化為字符串,(我主要是用此種方式傳這種格式的數據)例如

var arr = [ 0, 1, 2];
var myJSON = JSON.stringify(arr);
此時myJSON字符串就是'[0,1,2]',傳給后台接受

 后端代碼:

(@RequestParam(value = "systemType", required = false, defaultValue = "[]")String systemType)

//把前台傳來的數據('[0,1,2]')轉化為List
List<Interger> list = JSON.parseArray(systemType, Interger.class);

搜索搜出來的效果圖:

​ 

2.1.3  第三種方式,前台也可以傳這種類型的字符串(我偶爾用這樣方式,只是不太喜歡數組)

//前端構造出了"0,1,2,3" var systemType="0,1,2,3";

后端這樣解析

(@RequestParam(value = "systemType", required = false, defaultValue = "[]")String systemType)

//把前台傳來的數據('0,1,2')轉化為數組
Integer[] sectionItems = StringUtils.split(systemType, ",");

 

 如圖示:


 

2.2   像List<實體類>或List<Hashmap>的數據格式,有三種方式,看個人喜歡或公司規范自行選擇

       2.2.1  以傳list<實體類>為例

            java實體類

          

//部分代碼字段
public class ExamErrorQuestion {
    
    /**
     * 學生id號
     */
    private Integer studentId;
    
    /**
     * 考試表關聯id
     */
    private Integer examId;
    
    /**
     * 考試題目id
     */
    private Integer examQuestionId;
   
    .............................
}

 

 前端JavaScript構造數據

var examErrorQuestion= new Array(); 
examErrorQuestion.push({studentId: 2,examId: 1, examQuestionId:1});  
examErrorQuestion.push({studentId: 2,examId: 1, examQuestionId:2});  
examErrorQuestion.push({studentId: 2,examId: 1, examQuestionId:3});  
examErrorQuestion.push({studentId: 4,examId: 1, examQuestionId:1});  
examErrorQuestion.push({studentId: 4,examId: 1, examQuestionId:2});  
examErrorQuestion.push({studentId: 4,examId: 1, examQuestionId:3}); 
$.ajax({ 
  type: "POST", 
  url: "<%=basePath%>/exam/mark", 
  data: JSON.stringify(examErrorQuestion),//將js對象序列化成JSON字符串 
  dataType:"json", 
  contentType : 'application/json;charset=utf-8', //設置請求頭信息 
  success: function(data){ 
    … 
  }, 
  error: function(res){ 
    … 
  } 
}); 

 

后端Controller的java代碼,只寫中點解析數據

List<ExamErrorQuestion> eeqItems = JSON.parseArray(questions, ExamErrorQuestion.class);
//數據處理業務處理略

​ 

 

其實也可以不用實體類,也可以用Hashmao(看個人意願,要是公司有代碼量要求,可以用上面的解析),沒有代碼量要求,那就:

//解析試卷,沒有寫實體類,用Hashmap組裝數據格式 List<HashMap> paper = JSON.parseArray(tcbi.getPaperList(), HashMap.class); 


好多90%都是組裝的Hashmap,不喜歡維護那么多類,單重數據結構上看,HashMap是動態的實體類。

最后也可以用spring的原生注解接受:

   
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/mark", method = RequestMethod.POST)
    @LoginRequired
    @CrossOrigin
    public JSONObject mark(@CurrentUser User user,......
            @RequestBody List<ExamErrorQuestion> examErrorQuestion) {
略。。。
        }

 

3  實體類里有list,嵌套了一層(list純數字或list對象)

3.1  舉個工作中的例子,試卷有幾十道題目,教程有十幾個章節

 


嵌套類如下 

前端代碼:

var questions= new Array(); 
questions.push({title: "閏年二月多少天",type: 1,anwser:"A"});  //單選題
questions.push({title: "大數據組件有多少",type: 2,anwser:"hadoop,spark,hbase等"});  //問答題
questions.push({title: "傳輸層有哪些協議",type: 3, anwser:"AB"}); //多選題
。。。。。。。 

var paperInfo= {}; 
paperInfo.name = "大數據考試"; 
paperInfo.duration= "90分鍾";//考試時長
paperInfo.questions= questions; //題目列表
$.ajax({ 
  type: "POST", 
  url: "<%=basePath%>/paper/add", 
  data: JSON.stringify(paperInfo),//將對象序列化成JSON字符串 
  dataType:"json", 
  contentType : 'application/json;charset=utf-8', //設置請求頭信息 
  success: function(data){ 
    … 
  }, 
  error: function(res){ 
    … 
  } 
}); 

 

 后端接受主要代碼:

 @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @LoginRequired
    @CrossOrigin
    public JSONObjectsaveUsers(@RequestBody PaperInfo paperInfo) { 
    List<QuestionChoiceInfo> questions= paperInfo.getQuestions(); 
    //執行業務邏輯略。。。。。。 
  } 

不過我用的是分解法傳輸,主要也是fastjson


 

就先寫整理這么多了,囊括了各個傳輸數據的格式,開發就是把數據解析來解析去,組裝數據(特別是可視化項目) 。

總結下: 前后端交互數據就這三種數據格式

1, 單體的字符串,數字,布爾

2.   數組,list型

3.  實體類,HashMap型(按傳輸數據格式來說hashmap其實也算是動態實體,因為字段可增可減),組合嵌套型數據格式

 

 

早年開發時,數據交互是XML數據 、 來回構造解析

 

 

 

如今是json構造數據來回折騰,不兼容

 

 

看了此文,前后端交互的數據模型格式解析,也就到頭了!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM