007_请求返回Json

1. Json开发相关jar包

2. @RequestBody用于接收用户传入json串转成pojo

3. @ResponseBody把pojo转成json串响应用户

4. 例子

4.1. 新建一个名为SpringMVCJSON的Web工程, 拷入相关jar包, 同时加入jquery支持

4.2. 新建一个User.java的实体类

package com.lywgames.domain;

import java.io.Serializable;

public class User implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String name;
	private Integer age;

	public User() {	}

	public User(Integer id, String name, Integer age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
}

4.3. 新建一个JsonAction.java的处理器

package com.lywgames.web.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lywgames.domain.User;

@Controller
public class JsonAction {
	@RequestMapping("getJson")
	// @ResponseBody把pojo转成json串响应用户
	@ResponseBody
	// @RequestBody用于接收用户传入json串转成pojo
	public User getJson(@RequestBody User user) {
		System.out.println(user);
		user.setName("lisi");
		user.setAge(16);
		return user;
	}
}

4.4. 在src目录下新建springmvc.xml配置

4.5. 修改web.xml

4.6. 编写index.jsp

4.7. 运行项目

4.8. 发送请求, 把json类型的请求数据直接绑定给了实体类

4.9. 响应了json类型的数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值