在新建一个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:

  1. Spring 3 style type conversion through a ConversionService instance in addition to the JavaBeans PropertyEditors used for Data Binding.
  2. Support for formatting Number fields using the @NumberFormat annotation through the ConversionService.
  3. Support for formatting DateCalendarLong, and Joda Time fields using the @DateTimeFormat annotation.
  4. Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is present on the classpath.
  5. HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values from @RequestMapping or @ExceptionHandler methods.

    This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:

    1. ByteArrayHttpMessageConverter converts byte arrays.
    2. StringHttpMessageConverter converts strings.
    3. ResourceHttpMessageConverter converts to/from org.springframework.core.io.Resource for all media types.
    4. SourceHttpMessageConverter converts to/from a javax.xml.transform.Source.
    5. FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>.
    6. Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present and Jackson 2 XML extension is not present on the classpath.
    7. MappingJackson2HttpMessageConverter converts to/from JSON — added if Jackson 2 is present on the classpath.
    8. MappingJackson2XmlHttpMessageConverter converts to/from XML — added if Jackson 2 XML extension is present on the classpath.
    9. AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath.
    10. RssChannelHttpMessageConverter converts 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的更多相关文章

  1. springMVC中使用 RequestBody 及 Ajax POST请求 415 (Unsupported Media Type)

    使用POST请求的时候一直报错: Ajax 未设置 contentType 时会报 415 . 后台 RequestBody  承接前台参数,故对参数data的要求为“必传”“JSON”,否则会报40 ...

  2. SpringMVC 中HttpMessageConverter简介和Http请求415 Unsupported Media Type的问题

    一.概述: 本文介绍且记录如何解决在SpringMVC 中遇到415 Unsupported Media Type 的问题,并且顺便介绍Spring MVC的HTTP请求信息转换器HttpMessag ...

  3. [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢?

    [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢? 在ASP.NET Core应用程序中,接 ...

  4. HTTP Status 415 – Unsupported Media Type(使用@RequestBody后postman调接口报错)

    1.问题描述:使用springMVC框架后,添加数据接口中,入参对象没使用@RequestBody注解,造成postman发起post请求, from-data可以调通接口,但是raw调不通接口,然后 ...

  5. [JavaEE]调用Restful Service 出现415 Unsupported Media Type的问题(Rest Request Header中的Content-Type问题)

    用Chrome的插件Simple REST Client 调用POST的REST服务时,老是报415错误,如图. 一开始就以为是服务端的问题,各种google,百度,折腾了一下午未果. 晚上继续看,一 ...

  6. POST JSON fails with 415 Unsupported media type, SpringMVC

    网上的解决办法非常多,但是大多不靠谱. 归结原因:SpringMVC 无法通过 httprequest headers 中的 Content-Type 和 Accept 匹配到对应的HttpMessa ...

  7. spring中RequestBody注解接收参数时用JSONField转参数名无效问题

    问题: 在springboot项目中使用@RequestBody注解接收post请求中body里的json参数的情况.即: @RequestMapping(value = "/get-use ...

  8. springmvc之json交互406异常(Not Acceptable)和415异常(Unsupported Media Type)

    一. 406异常(Not Acceptable) 1. 没有添加jackson-databind包2. 请求的url的后缀是*.html.在springmvc中如果请求的后缀是*.html的话,是不可 ...

  9. SpringMVC过程中@RequestBody接收Json的问题 总是报415

    在SpringMVC中用@RequestBody接收Json的问题,总是报415,经过一翻查找 前台js的post: var postdata = '{"title":" ...

随机推荐

  1. 【CUDA开发】__syncthreads的理解

    __syncthreads()是cuda的内建函数,用于块内线程通信. __syncthreads() is you garden variety thread barrier. Any thread ...

  2. 配置Tomcat时退出就自动还原问题

    因为出现中文乱码问题需要配置server.xml文件,可是在每次配置完并且保存的情况下,重启服务器再看server.xml文件时,它自动还原到了未修改前的配置,后,解决如下: 第一步:打开eclips ...

  3. luoguP2015(简单树形DP)

    题目链接:https://www.luogu.org/problemnew/show/P2015 题意:给定一颗结点个数为n的树,有n-1条边,每条边有个权值,树根为1.现在给出q <=n,问剪 ...

  4. Palindromic Substrings

    Given a string, your task is to count how many palindromic substrings in this string. The substrings ...

  5. # 江西ccpc省赛-waves-(DP做法)

    江西ccpc省赛-waves-(DP做法) 题链:http://acm.hdu.edu.cn/showproblem.php?pid=6570 题意:给你长度为N,1≤N≤100000的一个数组,其中 ...

  6. Codeforces 1229C. Konrad and Company Evaluation

    传送门 首先考虑如何算出答案,考虑枚举中间那个点,显然每个点作为中间的点的次数为入度乘出度 所以答案就是每个点的入度乘出度之和 然后每个点开一个 $vector$ 维护从它出去的点数,每次修改的时候直 ...

  7. redis 学习(4)-- 哈希类型

    redis 学习(4)-- 哈希类型 介绍 redis 中哈希键值结构: 可以看出:哈希键值包括 key,field,value 这三部分,即键,属性,值这三部分.可以这样来表示: key, (fie ...

  8. innodb中一颗B+树能存储多少条数据

    如图,为B+树组织数据的方式: 实际存储时当然不会每个节点只存3条数据. 以InnoDB引擎为例,简单计算一下一颗B+树可以存放多少行数据. B+树特点:只有叶子节点存储数据,而非叶子节点存放的是用来 ...

  9. C++ 多态、虚函数(virtual 关键字)、静态联编、动态联编

    函数重写:(在子类中重写父类中的函数) 父类中被重写的函数  依然会继承  给子类. 子类中重写的函数将覆盖父类中的函数. 通过作用域分辨符  ::  可以访问到父类中的函数. 例如: #includ ...

  10. 类型(Type)

    A data type is homogeneous collection of values,effectiovely presented,equipped with a set of operat ...