spring mvc 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);
}

后台代码:

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;
}

 

输出

1:使用@responseBody来设置输出内容为context body (有方法注解/返回参数注解)
2:返回值设置为ResponseEntity<?>类型,以返回context body 

 

启用

<!-- 视图解析器和json解析器 -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="mediaTypes">
            <map>
                <entry key="html" value="text/html"/>
                <entry key="json" value="application/json"/>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/" /> <!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
                    <property name="suffix" value=".jsp"/>
                </bean>
            </list>
        </property>
        <property name="defaultViews">
            <list>
                <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
            </list>
        </property>
    </bean>

 

posted @ 2014-05-14 10:19  自行车上的程序员  阅读(1891)  评论(0编辑  收藏  举报