springmvc-Ajax-Objec返回值为Object


返回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>





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值