springmvc4.3.7中使用RequestBody,传入json参数时,得到错误415 Unsupported Media Type
在新建一个maven的项目的时候,当时并非springboot项目,是通过xml来配置的项目。在项目中DispatcherServlet的配置文件中配置了annotation-driven的,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <description>spring Configuration</description> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean> <context:component-scan base-package="org.xuan.springmvc.controller"
use-default-filters="false"><!-- base-package 如果多个,用“,”分隔 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" /> <!-- 子标签是用来添加扫描注解的 -->
</context:component-scan>
</beans>
后台接口定义方式:
@RequestMapping("testrequest")
@ResponseBody
public String testRequest(@RequestBody User user) throws Exception {
System.out.println(user);
return "OK";
}
User.java定义
package org.xuan.springmvc.model;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
前台请求方式:
$("#test").click(function () {
alert("aa")
var param={
id:1,
username:"test"
};
$.ajax({
url : "/testrequest",
type : "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(param),
success:function (data) {
alert(data)
}
});
})
结果发现不能请求成功:

发现请求类型不正确。
跟踪源码到AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters发现消息装换器messageConverters没有列出解析json格式的解析器:

查询文档https://docs.spring.io/spring-framework/docs/4.3.7.RELEASE/spring-framework-reference/html/mvc.html看默认的消息转换器有哪些
To enable MVC Java config add the annotation @EnableWebMvc to one of your @Configuration classes:
@Configuration
@EnableWebMvc
public class WebConfig { }
To achieve the same in XML use the mvc:annotation-driven element in your DispatcherServlet context (or in your root context if you have no DispatcherServlet context defined):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven/> </beans>
The above registers a RequestMappingHandlerMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver (among others) in support of processing requests with annotated controller methods using annotations such as @RequestMapping, @ExceptionHandler, and others.
It also enables the following:
- Spring 3 style type conversion through a ConversionService instance in addition to the JavaBeans PropertyEditors used for Data Binding.
- Support for formatting Number fields using the
@NumberFormatannotation through theConversionService. - Support for formatting
Date,Calendar,Long, and Joda Time fields using the@DateTimeFormatannotation. - Support for validating
@Controllerinputs with@Valid, if a JSR-303 Provider is present on the classpath. HttpMessageConvertersupport for@RequestBodymethod parameters and@ResponseBodymethod return values from@RequestMappingor@ExceptionHandlermethods.This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:
ByteArrayHttpMessageConverterconverts byte arrays.StringHttpMessageConverterconverts strings.ResourceHttpMessageConverterconverts to/fromorg.springframework.core.io.Resourcefor all media types.SourceHttpMessageConverterconverts to/from ajavax.xml.transform.Source.FormHttpMessageConverterconverts form data to/from aMultiValueMap<String, String>.Jaxb2RootElementHttpMessageConverterconverts Java objects to/from XML — added if JAXB2 is present and Jackson 2 XML extension is not present on the classpath.MappingJackson2HttpMessageConverterconverts to/from JSON — added if Jackson 2 is present on the classpath.MappingJackson2XmlHttpMessageConverterconverts to/from XML — added if Jackson 2 XML extension is present on the classpath.AtomFeedHttpMessageConverterconverts Atom feeds — added if Rome is present on the classpath.RssChannelHttpMessageConverterconverts RSS feeds — added if Rome is present on the classpath.
原来使用MappingJackson2HttpMessageConverter 需要引入相关的jar
然后引入包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
在调一次接口发现增加了json解析:

最后调用成功。
原因是在创建RequestMappingHandlerAdapter的时候加载messageConverters
public RequestMappingHandlerAdapter() {
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316
this.messageConverters = new ArrayList<HttpMessageConverter<?>>(4);
this.messageConverters.add(new ByteArrayHttpMessageConverter());
this.messageConverters.add(stringHttpMessageConverter);
this.messageConverters.add(new SourceHttpMessageConverter<Source>());
this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
在AllEncompassingFormHttpMessageConverter中会判断是否jvm是否加载了类com.fasterxml.jackson.databind.ObjectMapper和com.fasterxml.jackson.core.JsonGenerator,只有加载了才会创建
public AllEncompassingFormHttpMessageConverter() {
addPartConverter(new SourceHttpMessageConverter<Source>());
if (jaxb2Present && !jackson2XmlPresent) {
addPartConverter(new Jaxb2RootElementHttpMessageConverter());
}
if (jackson2Present) {
addPartConverter(new MappingJackson2HttpMessageConverter());
}
else if (gsonPresent) {
addPartConverter(new GsonHttpMessageConverter());
}
if (jackson2XmlPresent) {
addPartConverter(new MappingJackson2XmlHttpMessageConverter());
}
}
备注:
解析传入的参数是:AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters
解析返回值是:AbstractMessageConverterMethodProcessor#writeWithMessageConverters
springmvc4.3.7中使用RequestBody,传入json参数时,得到错误415 Unsupported Media Type的更多相关文章
- springMVC中使用 RequestBody 及 Ajax POST请求 415 (Unsupported Media Type)
使用POST请求的时候一直报错: Ajax 未设置 contentType 时会报 415 . 后台 RequestBody 承接前台参数,故对参数data的要求为“必传”“JSON”,否则会报40 ...
- SpringMVC 中HttpMessageConverter简介和Http请求415 Unsupported Media Type的问题
一.概述: 本文介绍且记录如何解决在SpringMVC 中遇到415 Unsupported Media Type 的问题,并且顺便介绍Spring MVC的HTTP请求信息转换器HttpMessag ...
- [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢?
[.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢? 在ASP.NET Core应用程序中,接 ...
- HTTP Status 415 – Unsupported Media Type(使用@RequestBody后postman调接口报错)
1.问题描述:使用springMVC框架后,添加数据接口中,入参对象没使用@RequestBody注解,造成postman发起post请求, from-data可以调通接口,但是raw调不通接口,然后 ...
- [JavaEE]调用Restful Service 出现415 Unsupported Media Type的问题(Rest Request Header中的Content-Type问题)
用Chrome的插件Simple REST Client 调用POST的REST服务时,老是报415错误,如图. 一开始就以为是服务端的问题,各种google,百度,折腾了一下午未果. 晚上继续看,一 ...
- POST JSON fails with 415 Unsupported media type, SpringMVC
网上的解决办法非常多,但是大多不靠谱. 归结原因:SpringMVC 无法通过 httprequest headers 中的 Content-Type 和 Accept 匹配到对应的HttpMessa ...
- spring中RequestBody注解接收参数时用JSONField转参数名无效问题
问题: 在springboot项目中使用@RequestBody注解接收post请求中body里的json参数的情况.即: @RequestMapping(value = "/get-use ...
- springmvc之json交互406异常(Not Acceptable)和415异常(Unsupported Media Type)
一. 406异常(Not Acceptable) 1. 没有添加jackson-databind包2. 请求的url的后缀是*.html.在springmvc中如果请求的后缀是*.html的话,是不可 ...
- SpringMVC过程中@RequestBody接收Json的问题 总是报415
在SpringMVC中用@RequestBody接收Json的问题,总是报415,经过一翻查找 前台js的post: var postdata = '{"title":" ...
随机推荐
- channel 介绍
!!!1.Memory Channel 内存通道 事件将被存储在内存中的具有指定大小的队列中. 非常适合那些需要高吞吐量但是失败是会丢失数据的场景下. 属性说明: !type – 类型,必须是“m ...
- 统计sql server 2012表的行数
--功能:统计sql server 2012表的行数 SELECT a.name, a.object_id, b.rows, b.index_id FROM sys.tables AS a INNER ...
- linux_文本编译使用命令
一:字符模式与shell命令 字符界面和图形界面 字符界面优点: 1):系统执行效率高,稳定性高,执行结果可直接返回 2):节省系统资源,对一个服务器至关重要 3):节省大量网络开销,大幅降低运行成本 ...
- PYQT5 pyinstaller 打包工程
win+R 输入cmd 回车 首先安装 pyinstaller : pip install pyinstaller 安装 pywin32: pip install pywin32 在cmd中输入工程 ...
- spark教程(四)-SparkContext 和 RDD 算子
SparkContext SparkContext 是在 spark 库中定义的一个类,作为 spark 库的入口点: 它表示连接到 spark,在进行 spark 操作之前必须先创建一个 Spark ...
- Redis利用Pipeline加速查询速度的方法
1. RTT Redis 是一种基于客户端-服务端模型以及请求/响应协议的TCP服务.这意味着通常情况下 Redis 客户端执行一条命令分为如下四个过程: 发送命令 命令排队 命令执行 返回结果 客户 ...
- linux下安装php的lua扩展
1. 进入管理员权限使用yum安装 readline(也可以使用wget下载后./configure 然后 make && make install进行安装) yum install ...
- 51nod 1251 Fox序列的数量 (容斥)
枚举最多数字的出现次数$k$, 考虑其他数字的分配情况. 对至少$x$种数出现$\ge k$次的方案容斥, 有 $\sum (-1)^x\binom{m-1}{x}\binom{n-(x+1)k+m- ...
- 封装H5ToApp方法
方法一: 新建个 Android studio 项目,用 webview 指定访问你的页面 方法二: 使用工具 cordova 附上地址:http://cordova.axuer.com/docs/ ...
- jQuery制作弹出窗(模态框)
来源:(二少)在南极 ##index.html <!DOCTYPE html><html lang="zh"><head> <meta c ...