springboot2.5.6对应hateoas1.3.5实现hal格式返回值

时间:2025-03-31 16:40:06
  • package ;
  • import ;
  • import ;
  • import ;
  • import .*;
  • import ;
  • import .*;
  • import .*;
  • @RestController
  • @RequestMapping("/books")
  • public class BookController {
  • private final BookModelAssemble bookModelAssemble = new BookModelAssemble();
  • @GetMapping("/{id}")
  • public EntityModel<Book> getOne(@PathVariable("id") Integer id){
  • Book book = new Book();
  • (id);
  • ("HAL入门");
  • EntityModel<Book> bookResource = (book);
  • return bookResource;
  • }
  • @GetMapping("")
  • public CollectionModel<EntityModel<Book>> getList(){
  • Book book = new Book();
  • (1);
  • ("HAL入门");
  • Book book1 = new Book();
  • book1.setId(2);
  • book1.setBookName("HAL进阶");
  • List<Book> books = new ArrayList();
  • books.add(book);
  • books.add(book1);
  • CollectionModel<EntityModel<Book>> bookResources = (books);
  • return bookResources;
  • }
  • @GetMapping("/page")
  • public PagedModel<EntityModel<Book>> getPageList(@RequestParam Integer index, @RequestParam Integer size){
  • List<Book> books = new ArrayList<>();
  • for (int i = 0; i < 10; i++) {
  • Book book = new Book();
  • (i);
  • ("HAL入门"+i);
  • books.add(book);
  • }
  • int total = books.size();
  • int start = (index - 1) * size + 1 > total ? total : (index - 1) * size +1;
  • int end = start + size > total ? total : start + size;
  • (start + "--" + end);
  • pageMetadata = new (size, index, total);
  • books = (start, end);
  • ArrayList<EntityModel<Book>> bookResources = new ArrayList<>();
  • for (Book book : books) {
  • bookResources.add((book));
  • }
  • PagedModel<EntityModel<Book>> pagedMode = new PagedModel<>(bookResources, pageMetadata, getAllLinks());
  • return pagedMode;
  • }
  • private List<Link> getAllLinks(){
  • ArrayList<Link> links = new ArrayList<>();
  • links.add(MvcLink.of(MvcLink.on(BookController.class).getOne(1)).withRel("item"));
  • links.add(MvcLink.of(MvcLink.on(BookController.class).getList()).withRel("list"));
  • links.add(MvcLink.of(MvcLink.on(BookController.class).getPageList(1, 10)).withSelfRel());
  • return links;
  • }
  • @GetMapping("/self")
  • public List<Book> getSelf(){
  • List<Book> list = ("http://127.0.0.1:8071/books", Book.class);
  • return list;
  • }
  • }