设计Code状态码
package com.itheima.controller;//状态码//通常是双方协议或公司规定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;}
- 设计Result返回数据规范
package com.itheima.controller;public class Result { //描述统一格式中的数据 private Object data; //描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败 private Integer code; //描述统一格式中的消息,可选属性 private String msg; // 注意:我们需要提供构造方法便捷操作 public Result() { } public Result(Integer code,Object data) { this.data = data; this.code = code; } public Result(Integer code, Object data, String msg) { this.data = data; this.code = code; this.msg = msg; } 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; }}
- 服务层返回数据更替
package com.itheima.controller;import com.itheima.domain.Book;import com.itheima.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; // 我们按照Result的构造方法以及实际需求提供返回值 // 我们可以根据三目运算符来直接输出其结果 @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}") 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); }}
经验总结扩展阅读
-
-
再过4天,鸿运当头,高人一等,喜事接踵,横财不断,尽享富贵
-
-
-
亚麻衣服怎么洗不缩水,亚麻面料的衣服这样清洗不会缩水?
-
导语:心仪的他就在眼前 心仪的男人不唐突的4种搭讪方式,教你把握机会,迈出追爱第一步
-
-
-
-
疾病 40岁是肠道疾病“高发期”,若想肠道更健康,3个坏习惯要改掉
-
-
-
-
-
-
-
-
2022年10月24日是出火的黄道吉日吗 2022年农历九月廿九宜出火吗
-
-
六款2023年最佳手机推荐 手机好用排行榜2023