目录
设置统一数据返回结果类
package com.liyang.controller;
/**
* @version 1.0
* @auter liyang
*/
public class Result {
private Object data;
private Integer code;
private String msg;
public Result(Integer code,Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Result(Integer code,Object data) {
this.data = data;
this.code = code;
}
public Result() {
}
public Object getData() {
return data;
}
public void setData(Object data) {
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;
}
}
注意事项
Result类中的字段并不是固定的,可以根据需要自行增减
提供若干个构造方法,方便操作
设置统一数据返回编码
package com.liyang.controller;
/**
* @version 1.0
* @auter liyang
*/
public class Code {
public static final Integer SAVE_OK=20011;
public static final Integer DELETE_OK=20021;
public static final Integer UPDATA_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 UPDATA_ERR=20030;
public static final Integer GET_ERR=20040;
}
注意事项
Code类的常量设计也不是固定的,可以根据需要自行增减,列如将查询再进行细分GET_OK
GET_ALL_OK,GET_PAGE_OK
根据情况设定合理的Result
package com.liyang.controller;
import com.liyang.domain.Book;
import com.liyang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/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.UPDATA_OK:Code.UPDATA_ERR,flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer 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);
Integer code=book !=null?Code.GET_OK:Code.GET_ERR;
String msg=book!=null? "":"数据查询失败";
return new Result(code,book,msg);
}
@GetMapping
public Result getAll() {
List<Book> booklist=bookService.getAll();
Integer code=booklist !=null?Code.GET_OK:Code.GET_ERR;
String msg=booklist!=null? "":"数据查询失败";
return new Result(code,booklist,msg);
}
}