1. 程式人生 > >自定義HttpMessageConverter接受JSON格式的資料

自定義HttpMessageConverter接受JSON格式的資料

 1.配置修改

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  5.     xmlns:util="http://www.springframework.org/schema/util"
  6.     xmlns:context="http://www.springframework.org/schema/context"
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans  
  9.         http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
  10.         http://www.springframework.org/schema/mvc  
  11.         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd       
  12.         http://www.springframework.org/schema/context  
  13.         http://www.springframework.org/schema/context/spring-context-4.2.xsd  
  14.         http://www.springframework.org/schema/util  
  15.         http://www.springframework.org/schema/util/spring-util-4.2.xsd">
  16.     <!-- spring可以自動去掃描base-pack下面的包或者子包下面的java檔案,  
  17.         如果掃描到有Spring的相關注解的類,則把這些類註冊為Spring的bean -->
  18.     <context:component-scanbase-package="com.control"/>
  19.     <!-- 使用預設的Servlet來響應靜態檔案 -->
  20.     <mvc:default-servlet-handler/>
  21.     <!-- 設定配置方案 -->
  22.     <mvc:annotation-driven>
  23.         <!-- 設定不使用預設的訊息轉換器 -->
  24.         <mvc:message-convertersregister-defaults="false">
  25.             <!-- 配置Spring的轉換器 -->
  26.             <beanclass="org.springframework.http.converter.StringHttpMessageConverter"/>
  27.             <beanclass="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
  28.             <beanclass="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
  29.             <beanclass="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
  30.             <!-- 配置fastjson中實現HttpMessageConverter介面的轉換器 -->
  31.             <beanid="fastJsonHttpMessageConverter"class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  32.                 <!-- 加入支援的媒體型別:返回contentType -->
  33.                 <propertyname="supportedMediaTypes">
  34.                     <list>
  35.                         <!-- 這裡順序不能反,一定先寫text/html,不然ie下會出現下載提示 -->
  36.                         <value>text/html;charset=UTF-8</value>
  37.                         <value>application/json;charset=UTF-8</value>
  38.                     </list>
  39.                 </property>
  40.             </bean>
  41.         </mvc:message-converters>
  42.     </mvc:annotation-driven>
  43.     <!-- 檢視解析器  -->
  44.      <beanid="viewResolver"
  45.           class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  46.         <!-- 字首 -->
  47.         <propertyname="prefix">
  48.             <value>/WEB-INF/content/</value>
  49.         </property>
  50.         <!-- 字尾 -->
  51.         <propertyname="suffix">
  52.             <value>.jsp</value>
  53.         </property>
  54.     </bean>
  55. </beans>

 注:以上的配置檔案和和之前的配置檔案重點的區別在於,之前使用的是spring中預設的Mapping-Jackson2HttpMessageConverter,這樣只需要配置預設的<mvc:annotation-driven/>就可以了。而現在使用了第三方的fastjson處理json資料,則需要另行配置HttpMessageConverter。

2.前端

 index.jsp

  1. <%@ page language="java"contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <!DOCTYPE html>
  4. <html>
  5. <head>
  6. <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
  7. <title>測試接收JSON格式的資料</title>
  8. <scripttype="text/javascript"src="js/jquery-1.11.0.min.js"></script>
  9. <scripttype="text/javascript"src="js/json2.js"></script>
  10. <scripttype="text/javascript">
  11. $(document).ready(function(){  
  12.     testRequestBody();  
  13. });  
  14. function testRequestBody(){  
  15.     $.ajax("${pageContext.request.contextPath}/json/testRequestBody",// 傳送請求的URL字串。  
  16.             {  
  17.            dataType : "json", // 預期伺服器返回的資料型別。  
  18.            type : "post", //  請求方式 POST或GET  
  19.            contentType:"application/json", //  傳送資訊至伺服器時的內容編碼型別  
  20.            // 傳送到伺服器的資料。  
  21.            data:JSON.stringify({id : 1, name : "Spring MVC企業應用實戰"}),  
  22.            async:  true , // 預設設定下,所有請求均為非同步請求。如果設定為false,則傳送同步請求  
  23.            // 請求成功後的回撥函式。  
  24.            success :function(data){  
  25.                console.log(data);  
  26.               $("#id").html(data.id);  
  27.               $("#name").html(data.name);  
  28.               $("#author").html(data.author);  
  29.            },  
  30.            // 請求出錯時呼叫的函式  
  31.            error:function(){  
  32.                alert("資料傳送失敗");  
  33.            }  
  34.     });  
  35. }  
  36. </script>
  37. </head>
  38. <body>
  39. 編號:<spanid="id"></span><br>
  40. 書名:<spanid="name"></span><br>
  41. 作者:<spanid="author"></span><br>
  42. </body>
  43. </html>

3.後端

 Book.Java

  1. package com.bean;  
  2. import java.io.Serializable;  
  3. publicclass Book implements Serializable {  
  4.     private Integer id;  
  5.     private String name;  
  6.     private String author;  
  7. 相關推薦

    定義HttpMessageConverter接受JSON格式資料

     1.配置修改 <?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.o

    定義HttpMessageConverter接受JSON格式的數

     1.配置修改 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http:/

    定義HTTPMessageConverter接收JSON格式資料

    jsp頁面 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); S

    定義HttpMessageConverter接受JSON數據

    exc date enc ready cep 方式 code -- 轉換成 Spring默認使用Jackson處理json數據。實際開發中,在業界中,使用非常受歡迎的fastjson來接受json數據。 創建一個項目,在web目錄下新建一個assets/js目錄,加入jqu

    fastjson和SpringMVC實現定義HttpMessageConverter接收和獲取JSON格式資料

    **引言**:Spring MVC 提供了處理JSON格式請求/響應的HttpMessageConverter利用Jackson 開源包處理JSON格式的請求響應訊息。 ```"關鍵技術"```:  **RequestBody**註解 :用於讀取Request請求

    使用fastjson與SpringMVC實現定義HttpMessageConverter接收和獲取JSON格式資料

    1.下載Spring、fastjson的jar包以及jQuery和json2的js檔案,向專案的WEB-INF/lib目錄加入Spring和fastjson的jar包,在WebContent目錄下建立一個js資料夾,向js資料夾中加入jQuery和json2的js檔案。 2

    定義HttpMessageConverter處理多個不同陣列形式的JSON資料

    需求 在一個成績管理系統中,有實體類Score和實體類Student,現需要對這兩個實體類關聯的資料庫表分別進行批量插入,因而需要處理兩種不同的JSON資料(均為陣列形式),並轉換為相應的List。在兩種實體類http請求中,Student類中的成員變數與對應

    Spring MVC接受JSON格式資料

    前端部分: index.jsp <%@ page language="java"contentType="text/html; charset=UTF-8"pageEncoding=

    一句python,一句R︱列表、元組、字典、資料型別、定義模組匯入(格式、去重)

    先學了R,最近剛剛上手python,所以想著將python和R結合起來互相對比來更好理解python。最好就是一句python,對應寫一句R。pandas中有類似R中的read.table的功能,而且很像。———————————————————————————————————

    SpringMVC定義返回XML/JSON資料

    1、新增jackson依賴 compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.0

    SpringMvc4.x---定義HttpMessageConverter

    bsp 定義 app nbsp res convert esp 大量 response 消息轉換器HttpMessageConverter是用來處理request和response裏面的數據的。Spring為我們內置了大量的HttpMessageConverter,例如,M

    [轉]使用定義HttpMessageConverter對返回內容進行加密

    返回結果 type 當前 solver png source nal list 自然 今天上午技術群裏的一個人問” 如何在 Spring MVC 中統一對返回的 Json 進行加密?”。 大部分人的第一反應是通過 Spring 攔截器(Interc

    定義擴展json 日期對象為例

    date ins x11 coder string 定義 bsp ring field import json from datetime import date from datetime import datetime class JsonCustomEn

    asp.net 輸出微信定義菜單json

    key reat select bsp empty mod 二級 根據 enum 不多說了直接上代碼 要引用 using LitJson; // 根據Menu列表生成符合微信規範的創建菜單JSon //一級菜單不超過3個,二級菜單不超過5個

    頁面訪問伺服器返回json格式資料太大,導致資料不全被截斷,無法展示

    問題:頁面展示呼叫查詢方法查詢全部資料的時候一直顯示loading。。。,開啟偵錯程式顯示 Failed to load resource: net::ERR_SPDY_PROTOCOL_ERROR,而少部分查詢則正常顯示。 因為資料中有圖片轉成的二進位制陣列,資料比較長,由此懷疑

    資料結構與演算法----定義類中函式與資料成員

    近期在梳理知識,做一個小結,希望自己能多多使用 在標頭檔案中: enum sign {plus, minus}; class Accruency { public: Accruency(sign s = plus, unsigned long d = 0, unsigned in

    Struts2返回json格式資料踩坑記錄

    事件起因 昨天提測修改凍結/解凍銀行卡樣式的功能,微姐測試過程中發現呼叫ajax請求耗時過長,今天來排查,發現瀏覽器請求/finance/ajax/freeze/ajaxGetShopLists時,對應的後端方法getShopList()莫名其妙地執行了兩遍,並且返回給瀏覽器的Json字串如下:

    js 處理動態json格式資料

    在json格式資料中,不直接獲取哪個key的資料,做迴圈處理時,是沒有size,length方法的 data:{ "暗咖": ["1.jpg"],   "灰藏青": ["2.jpg"] } for(var key in data) { //key 就是暗咖 //imga

    jQuery+Ajax+js請求json格式資料並渲染到html頁面

    1、先給json格式的資料: [ {"id":1,"name":"stan"}, {"id":2,"name":"jack"}, {"id":3,"name":"lucy"}, {"id":4,"name":"mary"}, {"id":5,"name":"jerry"}, {"id":6,"n

    js中從json格式資料中獲取特定物件

    寫個方法獲取: function getJsonValue(obj,name){ var result = null; var value = null; for(var key in obj){ valu