通常情况下,我们在用springmvc时,会直接返回查询到的分页对象。这时候,如果不做默认配置,会报出如题所示的错误:
[WARN ] 2018-07-16 19:00:20 org.springframework.web.servlet.mvc.support.DefaultHandlerException
Resolver Failed to write HTTP message: org.springframework.http.
converter.HttpMessageNotWritableException: No converter found for
return value of type: class com.xxx.springsecurity.common.Pager
原因就是,springmvc无法将对象直接转换为json对象,这时候,就需要我们来做配置,让springmvc在返回之前,先转换为json。
首先需要添加依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
接着在spring-mvc.xml配置文件中添加如下配置,指定Message对象转换器:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
至此,No converter found for return value of type报错问题解决。
补充一点:返回的对象中,如果不必要的字段不反回,可以通过@JsonIgnoreProperties来过滤,如果需要返回,一定要确保返回的字段有set,get方法。