您的位置:首页 > Web前端 > JavaScript

springmvc中,异步发送表单数据到Action,并响应Json文本返回(后端代码)

2017-09-14 15:13 561 查看
springmvc中,异步发送表单数据到Action,,并响应Json文本返回(后端代码)

1)导入jackson-core-asl-1.9.11.jar和jackson-mapper-asl-1.9.11.jar

2)在业务方法的返回值和权限之间使用@ResponseBody注解表示返回值对象需要转成JSON文本
3)在spring.xml配置文件中编写如下代码:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
EmpAction中

@Controller
@RequestMapping(value="/emp")
public class EmpAction {

/**
* @ResponseBody Emp 表示让springmvc将Emp对象转成json文本
*/
@RequestMapping(value="/bean2json")
public @ResponseBody Emp bean2json() throws Exception{
//创建Emp对象
Emp emp = new Emp();
emp.setId(1);
emp.setUsername("哈哈");
emp.setSalary(7000D);
emp.setHiredate(new Date());
return emp;
}

@RequestMapping(value="/listbean2json")
public @ResponseBody List<Emp> listbean2json() throws Exception{
//创建List对象
List<Emp> empList = new ArrayList<Emp>();
//向List对象中添加三个Emp对象
empList.add(new Emp(1,"哈哈",7000D,new Date()));
empList.add(new Emp(2,"呵呵",8000D,new Date()));
empList.add(new Emp(3,"嘻嘻",9000D,new Date()));
//返回需要转JSON文本的对象
return empList;
}

@RequestMapping(value="/map2json")
public @ResponseBody Map<String,Object> map2json() throws Exception{
//创建List对象
List<Emp> empList = new ArrayList<Emp>();
//向List对象中添加三个Emp对象
empList.add(new Emp(1,"哈哈",7000D,new Date()));
empList.add(new Emp(2,"呵呵",8000D,new Date()));
empList.add(new Emp(3,"嘻嘻",9000D,new Date()));
//创建Map对象
Map<String,Object> map = new LinkedHashMap<String,Object>();
//向Map对象中绑定二个变量
map.put("total",empList.size());
map.put("rows",empList);
//返回需要转JSON文本的对象
return map;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springmvc Json返回
相关文章推荐