• 前后端分离项目(九):实现"添加"功能(后端接口)


    好家伙,来了来了,”查“已经完成了,现在是“增”

     

    前端的视图已经做好了,现在我们来完善后端

    后端目录结构

     

     

    完整代码在前后端分离项目(五):数据分页查询(后端接口) - 养肥胖虎 - 博客园 (cnblogs.com)

     

    我们来看我们的接口代码:

    复制代码
    package com.example.demo2.controller;
    
    import com.example.demo2.entity.Book;
    import com.example.demo2.repository.BookRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @RequestMapping("/book")
    public class BookHandler {
        @Autowired
        private BookRepository bookRepository;
    
        @GetMapping("/findAll/{page}/{size}")
        public Page findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
            PageRequest request = PageRequest.of(page-1,size);
            return bookRepository.findAll(request);
        }
    
        @PostMapping("/save")
        public String save(@RequestBody Book book){
            Book result = bookRepository.save(book);
            if(result != null){
                return "success";
            }else{
                return "error";
            }
        }
    
        @GetMapping("/findById/{id}")
        public Book findById(@PathVariable("id") Integer id){
            return bookRepository.findById(id).get();
        }
    
        @PutMapping("/update")
        public String update(@RequestBody Book book){
            Book result = bookRepository.save(book);
            if(result != null){
                return "success";
            }else{
                return "error";
            }
        }
    
        @DeleteMapping("/deleteById/{id}")
        public void deleteById(@PathVariable("id") Integer id){
            bookRepository.deleteById(id);
        }
    }
    复制代码

     

        @PostMapping("/save")
        public String save(@RequestBody Book book){
            Book result = bookRepository.save(book);
            if(result != null){
                return "success";
            }else{
                return "error";
            }
        }

    前端的接口调用记得改

    复制代码
    
    
    
    复制代码

     

    我们的数据库表:

     

     来了,让我们看看效果吧

     

     

    成了,卧槽,终于tmd成了,

     

     

     

  • 相关阅读:
    SpringCloudGateway集成SpringDoc CORS问题
    MongoDB 全方位知识图谱
    docker总结
    【Java Web】论坛——我收到的赞
    CPP的uint32_t类型简介
    gRPC入门学习之旅(六)
    软件测试测试常见分类有哪些?
    你们的优雅停机真的优雅吗?
    开发一款流行的国内App可能用到的SDK功能分析
    WIN10系统安装RabbitMQ
  • 原文地址:https://www.cnblogs.com/FatTiger4399/p/16840332.html