zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringMVC 访问controller层出错:No converter found for return value of type: class java.util.HashMap

JAVASpringMVC for 访问 of type value No
2023-06-13 09:15:55 时间

在使用SSM整合的时候,spring mvc 添加@ResponseBody的时候,正常情况下都会返回json的。但是又的时候如果没有配置好的话,如果想要返回Map的json对象会报:No converter found for return value of type: class java.util.HashMap错误。

如下图:

如果返回的事字符串或者事Integer类型就可以正常返回,但是如果返回对象的话,就会出现这个错误。说明在spring mvc转换成json的时候出错了。

解决方案一:

查看pom.xml是否添加了jackson相关的jar.

我们知道spring mvc默认使用的事jackson来转换json的。如果没有的话,添加上即可。

方案二:

如果不想在pom.xml中添加的话,可以在spring-mvc.xml中添加如下配置:

<!-- 启动Springmvc注解驱动 -->
    <mvc:annotation-driven/>
 <!-- 返回json 方法一 需要导入 fastjson.jar包 -->  
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="false">
            <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
            <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>