1. 程式人生 > 其它 >springmvc之json互動

springmvc之json互動

操作json需要的jar包

jackson-annotations-2.9.9.jar
jackson-core-2.9.9.jar
jackson-databind-2.9.9.3.jar

下載:https://repo1.maven.org/maven2/com/fasterxml/jackson/core/

一、引入jar包

二、配置json轉換器

<!--註解介面卡 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <
property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>

注意:如果使用<mvc:annotation-driven /> 則不用單獨配置json轉換器

三、json互動測試

Ⅰ、請求資料格式json、輸出資料格式json

  頁面定義

//請求json,輸出是json
function requestJson(){
    
    $.ajax({
        type:'post',
        url:'${pageContext.request.contextPath }/requestJson.action',
        contentType:'application/json;charset=utf-8',
        //資料格式是json串,商品資訊
        data:'{"name":"手機","price":999}',
        success:
function(data){//返回json結果 alert(data); } }); }

  controller方法定義

    //請求json串(商品資訊),輸出json(商品資訊)
    //@RequestBody將請求的商品資訊的json串轉成itemsCustom物件
    //@ResponseBody將itemsCustom轉成json輸出
    @RequestMapping("/requestJson")
    public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){
        
        //@ResponseBody將itemsCustom轉成json輸出
        return itemsCustom;
    }

Ⅱ、請求資料格式key/value、輸出資料格式json

  頁面定義

//請求key/value,輸出是json
function responseJson(){
    
    $.ajax({
        type:'post',
        url:'${pageContext.request.contextPath }/responseJson.action',
        //請求是key/value這裡不需要指定contentType,因為預設就 是key/value型別
        //contentType:'application/json;charset=utf-8',
        //資料格式是json串,商品資訊
        data:'name=手機&price=999',
        success:function(data){//返回json結果
            alert(data.name);
        }
        
    });
    
}

  controller方法定義

    //請求key/value,輸出json
    @RequestMapping("/responseJson")
    public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){
        
        //@ResponseBody將itemsCustom轉成json輸出
        return itemsCustom;
    }

四、總結

  ①、請求資料格式

    json,使用@RequestBody來接收

    key/value,使用@RequestMapping來接收

  ②、輸出資料格式就只有json,使用@ResponseBody修飾返回型別