1.在controller层定义Result类用于表现层与前端进行通信
Result类:
package com.itheima.controller;
import org.springframework.web.bind.annotation.RestController;
public class Result {
private Object data;
private Integer code;
private String msg;
public Result(Object data, Integer code, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
public Result(Object data, Integer code) {
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;
}
}
2.在controller层定义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;
}
3.将协议运用到表现层,其中使用了三目表达式
BookController类:
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.apache.ibatis.annotations.Delete;
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,flag ? Code.SAVE_OK:Code.SAVE_ERR);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag=bookService.update(book);
return new Result(flag,flag ? Code.UPDATE_OK:Code.UPDATE_ERR);
}
@DeleteMapping("/{id}")
public Result deleteById(@PathVariable Integer id) {
boolean flag=bookService.deleteById(id);
return new Result(flag,flag ? Code.DELETE_OK:Code.DELETE_ERR);
}
@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(book,code,msg);
}
@GetMapping
public Result getAll() {
List<Book> books=bookService.getAll();
Integer code=books !=null ? Code.GET_OK : Code.GET_ERR;
String msg=books !=null ? " " : "数据查询失败,请重试!";
return new Result(books,code,msg);
}
}