• 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>
  • 相关阅读:
    java通过UUID生成16位唯一订单号
    spring framework体系结构及内部各模块jar之间的maven依赖关系
    Java操作PDF之iText超入门
    对象拷贝
    Alluxio 1.5集群搭建
    InfluxDb中写入重复数据问题解决方案
    苹果笔记本中为虚拟机扩充硬盘的方法
    Grafana中整个Dashboard报错问题解决
    使用WebEx录制视频并转换为MP4
    Spark配置参数优先级
  • 原文地址:https://www.cnblogs.com/yangzhilong/p/3727135.html
Copyright © 2020-2023  润新知