欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC 访问Controller 报错:e No converter found for return value of type: class java.util.ArrayLis

程序员文章站 2022-03-26 22:33:59
...

1、controller方法如下:

@RequestMapping("/a2")
public  List<User>    ajaxtest(){
    List<User> userList = new ArrayList<User>();
    userList.add(new User("妗妗1",1,"女"));
    userList.add(new User("妗妗12",2,"女"));
    userList.add(new User("妗妗13",3,"女"));
    User user4 = new User("妗妗14",1,"女");
    System.out.println(userList);

    return userList;
}

2、请求该方法,返回如下信息

SpringMVC 访问Controller 报错:e No converter found for return value of type: class java.util.ArrayLis

 

3、经查明,是controller 不支持直接返回对象,可将java对象,转为json对象,再返回。

导入json包,并配置对象转换成json对象的配置后,可直接返回对象,具体步骤如下

(1)导入jackjson包

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.9.8</version>

</dependency>

(2)配置json乱码问题

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg value="UTF-8"/>
        </bean>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                    <property name="failOnEmptyBeans" value="false"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

4、再次方法该方法,正常。

 

@RequestMapping("/a2")
public List<User> ajaxtest(){
List<User> userList = new ArrayList<User>();
userList.add(new User("妗妗1",1,"女"));
userList.add(new User("妗妗12",2,"女"));
userList.add(new User("妗妗13",3,"女"));
User user4 = new User("妗妗14",1,"女");
System.out.println(userList);

return userList;
}
相关标签: json