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


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

     

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

    后端目录结构

     

     

    完整代码在前后端分离项目(五):数据分页查询(后端接口) - 养肥胖虎 - 博客园 (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成了,

     

     

     

  • 相关阅读:
    Java大厂面试题第2季
    Mapbox实战项目(1)-栅格图片图层实现地图方位展示
    AntPathMatcher【Spring中提供的路径匹配器】
    机器学习常见降维方法及Python示例汇总【附完整代码】
    python面向对象继承开发时遇到情况——方法的重写(覆盖、扩展)
    Leetcode—283.移动零【简单】
    再谈毕业论文设计投机取巧之IVR自动语音服务系统设计(信息与通信工程专业A+其实不难)
    Spring Boot 中的过滤器 (Filter) 使用方案
    第十九章总结:Java绘图
    react 实现chatGPT的打印机效果 兼容富文本,附git地址
  • 原文地址:https://www.cnblogs.com/FatTiger4399/p/16840332.html