zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Finalize,Dispose,SuppressFinalize
    防火防盗防微软,Firefox发布插件自动检测服务
    Nginx的Rewrite设置及示例
    Linux游戏开发包 ClanLib 2.1.0 发布
    HTTP协议详解(真的很经典)
    Linux on POWER:发行版迁移和二进制兼容性考虑事项
    映射网络驱动器VBS脚本
    [笔记] 使用 opcache 优化生产环境PHP
    2020最新版MySQL数据库面试题(三)
    请注意,面试中有这7个行为肯定会被拒绝!
  • 原文地址:https://www.cnblogs.com/yangzhilong/p/3727135.html
Copyright © 2011-2022 走看看