响应数据
定义
@ResponseBody注解可将方法返回值直接响应给浏览器
如果返回值类型是 实体对象/集合 ,将会转换为JSON格式响应
@ResponseBody作用在Controller方法上/类上,因此也叫方法注解/类注解
@RestController = @Controller + @ResponseBody
统一响应
实体对象
//实体对象
public class Result {
//响应码,1 代表成功; 0 代表失败
private Integer code;
//提示信息
private String msg;
//返回的数据
private Object data;
public Result() {
}
public Result(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
//查询 成功响应(把查询结果做为返回数据响应给前端)
public static Result success(Object data){
return new Result(1, "success", data);
}
//增删改 成功响应(不需要给前端返回数据)
public static Result success(){
return new Result(1, "success", null);
}
//失败响应
public static Result error(String msg){
return new Result(0, msg, null);
}
}
controller方法
@RestController
public class ResponseController {
//controller方法1
@RequestMapping("/hello")
public Result hello(){
System.out.println("Hello World ~");
//return new Result(1,"success","Hello World ~");
return Result.success("Hello World ~");
}
//controller方法2
@RequestMapping("/getAddr")
public Result getUser(){
Address addr = new Address();//实体对象
addr.setProvince("广东");
addr.setCity("深圳");
return Result.success(addr);
}
//controller方法3
@RequestMapping("/listAddr")
public Result listAddr(){
List<Address> list = new ArrayList<>();//集合数据
Address addr = new Address();
addr.setProvince("广东");
addr.setCity("深圳");
Address addr2 = new Address();
addr2.setProvince("陕西");
addr2.setCity("西安");
list.add(addr);
list.add(addr2);
return Result.success(list);
}
}
响应数据
//响应数据1
{
"code": 1,
"msg": "success",
"data": "Hello World ~"
}
//响应数据2
{
"code": 1,
"msg": "success",
"data": {
"province": "广东",
"city": "深圳"
}
}
//响应数据3
{
"code": 1,
"msg": "success",
"data": [
{
"province": "广东",
"city": "深圳"
}
{
"province": "陕西",
"city": "西安"
}
]
}
来自上海