Spring MVC 學習筆記 json格式的輸入和輸出

encn 9年前發布 | 87K 次閱讀 Spring MVC Web框架

Spring mvc處理json需要使用jackson的類庫,因此為支持json格式的輸入輸出需要先修改pom.xml增加jackson包的引用

 <!-- json -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-lgpl</artifactId>
            <version>1.8.1</version>
        </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-lgpl</artifactId>
        <version>1.8.1</version>
    </dependency></pre> <p></p>

先修改之前的helloworld.jsp,增加客戶端json格式的數據輸入。

var cfg =     {
        type: 'POST', 
        data: JSON.stringify({userName:'winzip',password:'password',mobileNO:'13818881888'}), 
        dataType: 'json',
        contentType:'application/json;charset=UTF-8',        
        success: function(result) { 
            alert(result.success); 
        } 
    }; function doTestJson(actionName){
    cfg.url = actionName;
    $.ajax(cfg);
}

根據前面的分析,在spring mvc中解析輸入為json格式的數據有兩種方式 1:使用@RequestBody來設置輸入

@RequestMapping("/json1")
    @ResponseBody public JsonResult testJson1(@RequestBody User u){
        log.info("get json input from request body annotation");
        log.info(u.getUserName()); return new JsonResult(true,"return ok");
}

2:使用HttpEntity來實現輸入綁定

@RequestMapping("/json2") public ResponseEntity<JsonResult> testJson2(HttpEntity<User> u){
        log.info("get json input from HttpEntity annotation");
        log.info(u.getBody().getUserName());
        ResponseEntity<JsonResult> responseResult = new ResponseEntity<JsonResult>(          new JsonResult(true,"return ok"),HttpStatus.OK);      return responseResult;
}

Json格式的輸出也對應有兩種方式 1:使用@responseBody來設置輸出內容為context body 2:返回值設置為ResponseEntity<?>類型,以返回context body 另外,第三種方式是使用ContentNegotiatingViewResolver來設置輸出為json格式,需要修改servlet context配置文件如下

 <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            </list>
        </property>
        <property name="ignoreAcceptHeader" value="true" />
    </bean>

但這種格式的輸出會返回{model類名:{內容}} 的json格式, 例如,以下代碼

@RequestMapping("/json3.json") public JsonResult testJson3(@RequestBody User u){
        log.info("handle json output from ContentNegotiatingViewResolver");         return new JsonResult(true,"return ok");
    }

期望的返回是 {success:true,message:”return ok”}; 但實際返回的卻是 {"jsonResult":{"success":true,"msg":"return ok"}} 原因是MappingJacksonJsonView中對返回值的處理未考慮modelMap中只有一個值的情況,直接是按照mapName:{mapResult}的格式來返回數據的。 修改方法,重載MappingJacksonJsonView類并重寫filterModel方法如下

protected Object filterModel(Map<String, Object> model) {  
        Map<?, ?> result = (Map<?, ?>) super.filterModel(model); if (result.size() == 1) 
        { return result.values().iterator().next();  
        } else { return result;  
        }  
    }

對應的ContentNegotiatingViewResolver修改如下

 <bean
        class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1" />
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json" />
            </map>
        </property>
        <property name="defaultViews">
            <list>
                <bean
                    class="net.zhepu.json.MappingJacksonJsonView" />
            </list>
        </property>
        <property name="ignoreAcceptHeader" value="true" />
    </bean>

 

 本文由用戶 encn 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!