返回Object时需要注意的问题:
处理器方法返回的Object对象,是作为数据出现的,而不是作为视图出现的。
返回Object数据的应用场景是,服务端向AJAX请求作为响应。
将Object数据传递给页面,需要HttpMessageConverter将其转换为JSON,而这个转换适配器类对象是由JACKSON充当。所以需要导入JACKSON的Jar包;需要注册MVC注解驱动。
转换为JSON的处理器方法返回对象,是存放在响应体中的,所以需要处理器告知系统,该返回值要存放到响应体中。在处理器方法前添加@ResponseBody注解。
package com.abc.beans;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + " ]";
}
package com.abc.handlers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.abc.beans.Student;
@Controller
@RequestMapping("/some")
public class SomeHandler {
//一旦使用了produce,那么系统将不使用httpMessageConverter适配器
/*@RequestMapping(value="/myAjax.do", produces="text/html;charset=UTF-8")
@ResponseBody
public String doAjax( ) { 这是返回String的方法
return "啊啊啊111";
}*/
@RequestMapping(value="/myAjax.do")
@ResponseBody
public Student doAjax( ) { /*返回值为Object自定义类型*/
return new Student("张三",11);
}
}
}
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<!-- 注册组件扫描器 -->
<context:component-scan base-package="com.abc.handlers" />
<!-- 注解mvc驱动 -->
<mvc:annotation-driven />
</beans>