在新建一個maven的項目的時候,當時並不是springboot項目,是經過xml來配置的項目。在項目中DispatcherServlet的配置文件中配置了annotation-driven的,html
<?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>
後臺接口定義方式:java
@RequestMapping("testrequest") @ResponseBody public String testRequest(@RequestBody User user) throws Exception { System.out.println(user); return "OK"; }
User.java定義git
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; } }
前臺請求方式:github
$("#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) } }); })
結果發現不能請求成功:web
發現請求類型不正確。ajax
跟蹤源碼到AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters發現消息裝換器messageConverters沒有列出解析json格式的解析器:spring
查詢文檔https://docs.spring.io/spring-framework/docs/4.3.7.RELEASE/spring-framework-reference/html/mvc.html看默認的消息轉換器有哪些express
To enable MVC Java config add the annotation @EnableWebMvc
to one of your @Configuration
classes:json
@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):spring-mvc
<?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:
@NumberFormat
annotation through the ConversionService
.Date
, Calendar
, Long
, and Joda Time fields using the @DateTimeFormat
annotation.@Controller
inputs with @Valid
, if a JSR-303 Provider is present on the classpath.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:
ByteArrayHttpMessageConverter
converts byte arrays.StringHttpMessageConverter
converts strings.ResourceHttpMessageConverter
converts to/from org.springframework.core.io.Resource
for all media types.SourceHttpMessageConverter
converts to/from a javax.xml.transform.Source
.FormHttpMessageConverter
converts form data to/from a MultiValueMap<String, String>
.Jaxb2RootElementHttpMessageConverter
converts Java objects to/from XML — added if JAXB2 is present and Jackson 2 XML extension is not present on the classpath.MappingJackson2HttpMessageConverter
converts to/from JSON — added if Jackson 2 is present on the classpath.MappingJackson2XmlHttpMessageConverter
converts to/from XML — added if Jackson 2 XML extension is present on the classpath.AtomFeedHttpMessageConverter
converts Atom feeds — added if Rome is present on the classpath.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