1.定义Restful类
说明:使用@Data
注解是Lombok库提供的一个注解,用于自动生成类的getter、setter、equals、hashcode和toString方法。
package com.forever.controller.utils;import lombok.Data;@Data
public class Restful {private Boolean flag;//data是任意类型private Object data;public Restful() {}public Restful(Boolean flag) {this.flag = flag;}public Restful(Boolean flag,Object data){this.flag=flag;this.data=data;}
}
2. BookController
说明:Spring MVC控制器,用于处理与图书相关的HTTP请求。
package com.forever.controller;import com.forever.controller.utils.Restful;
import com.forever.domain.Book;
import com.forever.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;//注释这个就不会注册成bean了
@RestController
@RequestMapping("/books")
public class BookController {// 提供若干功能@Autowiredprivate IBookService bookService;@GetMappingpublic Restful getAll() {return new Restful(true, bookService.list());
// return bookService.list();}@PostMapping
// 通过请求体传json数据public Restful save(@RequestBody Book book) {
// 书写过于复杂,去类里面写方法
// Restful r=new Restful();
// boolean flag=bookService.save(book);
// r.setFlag(flag);
// return r;return new Restful(bookService.save(book));}@PutMappingpublic Restful update(@RequestBody Book book) {
// return bookService.modify(book);return new Restful(bookService.modify(book));}@DeleteMapping("{id}")public Restful delete(@PathVariable Integer id) {return new Restful(bookService.delete(id));
// return bookService.delete(id);}@GetMapping("{id}")public Restful getById(@PathVariable Integer id) {
// return bookService.getById(id);return new Restful(true, bookService.getById(id));}@GetMapping("{currentPage}/{pageSize}")public Restful getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
// return bookService.getPage(currentPage, pageSize);return new Restful(true, bookService.getPage(currentPage, pageSize));}
}
3.数据库结构