今天在项目中使用SpringMVC框架,想从前台往后台发送json格式的数据。但是发送失败,查看开发者工具栏。

分别得到了两个错误码:400、415

查询错误码详情了解到

ajax请求后台数据时报 HTTP 400 错误 - 请求无效 (Bad request);出现这个请求无效报错说明请求没有进入到后台服务里;
原因:1)前端提交数据的字段名称或者是字段类型和后台的实体类不一致,导致无法封装;
          2)前端提交的到后台的数据应该是json字符串类型,而前端没有将对象转化为字符串类型;
解决方案:
1)对照字段名称,类型保证一致性

2)使用stringify将前端传递的对象转化为字符串    data: JSON.stringify(param)  ;

ajax请求后台数据报 HTTP 415 错误 - 服务器无法处理请求附带的媒体格式 (Unsupported Media Type);

1)原因可能有springmvc没有添加配置,注解;

2)pom.xml没有jackson包的引用;

3)Ajax请求时没有设置Content-Type为application/json;charset=utf-8

4)发送请求内容没有发送json字符串,而是以json格式数据发送的

解决方案:

1)检查springMVC配置文件是否开启了注解

使用SpringMVC前台发送数据时得到400或415错误!

2)maven引入jackson包:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

3)设置contentType为 使用SpringMVC前台发送数据时得到400或415错误!

4)发送数据的格式

使用SpringMVC前台发送数据时得到400或415错误!使用SpringMVC前台发送数据时得到400或415错误!


最后注意:不要将二者搞混,要不然不是得到400就是得到415

使用SpringMVC前台发送数据时得到400或415错误!


下面引入一个链接:Json对象和Json字符串的区别

相关文章:

  • 2021-11-20
  • 2022-12-23
  • 2021-09-17
  • 2021-11-08
  • 2022-12-23
  • 2021-11-10
  • 2022-12-23
  • 2021-08-10
猜你喜欢
  • 2021-12-28
  • 2021-05-14
  • 2022-12-23
  • 2021-09-06
  • 2021-04-09
  • 2021-12-10
  • 2021-12-08
相关资源
相似解决方案