1. 设置统一数据返回结果类:com.feiyan.controller包下创建Result类
public class Result
{
private Integer code;
public Integer getCode(){ retutn code; }
public void setCode(Integer code){ this.code = code; }
private Object data;
public Object getData(){ return data; }
public void setData(Object data){ this.data = data; }
private String msg;
public String getMsg(){ return msg; }
public void setMsg(String msg){ this.msg = msg; }
public Result(){}
public Result(Integer code, Object data)
{
this.code = code;
this.data = data;
}
public Result(Integer code, Object data, String msg)
{
Result(code, data);
this.msg = msg;
}
}
2. 创建code常量:com.feiyan.controller包下创建Code类
public class Code
{
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
}
2. 修改BookController类中方法的返回
@RestController
@ResuestMapping("/books")
public class BookController
{
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book)
{
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
}
@PutMapping
public Result update(@RequestBody Book book)
{
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
}
@DeleteMapping("/{id}")
{
boolean flag = bookService.delete(id);
return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id)
{
Book book = bookService.getById(id);
if(book == null)
{
return new Result(Code.GET_ERR, book, "数据查询失败,请稍后再试!");
}
else
{
return new Result(Code.GET_OK, book, "");
}
}
@GetMapping
public Result getAll()
{
List<Book> bookLst = bookService.getAll();
if(bookLst == null)
{
return new Result(Code.GET_ERR, bookLst, "数据查询失败,请稍后再试!");
}
else
{
return new Result(Code.GET_OK, bookLst, "");
}
}
}
浙公网安备 33010602011771号