zoukankan      html  css  js  c++  java
  • springmvc 使用jq传递json数据时出现415错误

    出现415错误是因为解析json时出现了错误,通过排查几点就能解决。

    样例:

    <script>
    function requestByJson() {
        
        var datatest = {"id":0,"username":"kinome","password":"pwd"};
    
        $.ajax({
    
                  type : 'post',
    
                  url : '${pageContext.request.contextPath}/updateUserInfo.action',
    
                  dataType:"json",
                  
                  //设置contentType类型为json
    
                  contentType : 'application/json;charset=utf-8',
    
                  //json数据
    
                  data : JSON.stringify(datatest),
    
                  //请求成功后的回调函数
    
                  success : function(data) {
    
                           alert(data.id+" "+data.username+" "+data.password);
    
                  }
    
        });
    
    }
    </script>

    必须设置:

    dataType:"json"
    contentType : 'application/json;charset=utf-8'
    data : JSON.stringify(存放json的变量)    // 这里存在一个对象的问题,所以需要封装起来使用

    controller方面:

    必须配置: consumes = "application/json" 用来接收json数据

    (按照上图的编写方式就能正常接收并返回json数据)

    spring所有依赖版本: 4.1.7.RELEASE

    spring-servlet.xml 必须配置 <mvc:annotation-driven /> 用来进行自动注册并加载jackson相关文件

    pom.xml必须配置jackson相关依赖,且 (重点)spring版本和jackson版本如果不兼容也会导致无法解析json,进而提示415错误

            <!--jackson相关依赖 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.5.4</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.5.4</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.5.4</version>
            </dependency>




    成功返回json数据并通过jq的回调函数执行:

  • 相关阅读:
    服务器常用端口
    xml处理类
    水印的代码
    Asp.net常用的51个代码(非常实用)
    poj 2453
    MOD
    LIS(最长上升子序列)
    POJ各题算法分类(转)
    poj 1496&1850
    poj 1423
  • 原文地址:https://www.cnblogs.com/kinome/p/8744986.html
Copyright © 2011-2022 走看看