仓库地址

w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started quickly through a series of examples (github.com)

Chapter04-基于SpringBoot的书籍管理Web服务

从本章开始,我们将会基于SpringBoot框架,来编写一块书籍管理的应用。为了契合我们的简单教程原则,项目不会出现复杂的结构,只会有一个通用的结构。

初始结构

我们项目的初始结构如下:

base-package
|-- controller
|-- BookController.class
|-- model
|-- Book.class
BookManagementSystemApp.class

Book类

public class Book {
/**
* 书籍ID
*/
private String id;
/**
* 书籍名称
*/
private String name;
/**
* 书籍价格
*/
private double price; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
}
}

BookController类

@RestController
@RequestMapping("books") // url:"books"
public class BookController { private final List<Book> bookList; /**
* 构造函数
* 内部进行bookList初始化操作,便于下面的测试
*/
public BookController() {
int count = 3;
this.bookList = new ArrayList<>(count);
Random random = new Random();
for (int idx = 0; idx < count; idx++) { Book book = new Book();
book.setId(Integer.toString(idx));
book.setName("book@" + idx);
book.setPrice(random.nextInt(100) + 1); this.bookList.add(book);
}
} /**
* GET /books
* 返回所有的书籍信息
*/
@GetMapping
public List<Book> getBookList() {
return bookList;
} /**
* GET /books/{id}
* 根据书籍ID,得到对应的书籍信息
* @param id 书籍ID
* @return 书籍
*/
@GetMapping("{id}")
public Book getBookById(@PathVariable("id") String id) {
Optional<Book> first = this.bookList
.stream()
.filter(b -> b.getId().equals(id))
.findFirst();
return first.orElse(null);
} /**
* POST /books
* 添加书籍信息
* 需要注意的是,入参Book需要添加注解@RequestBody,才能通过HTTP JSON形式传入
* @param book 希望新增的书籍信息
*/
@PostMapping
public void addBook(@RequestBody Book book) {
if (book == null) {
System.out.println("请求数据book为空,未进行添加");
return;
}
// 服务端生成ID
String nextId = Integer.toString(this.bookList.size());
book.setId(nextId);
this.bookList.add(book);
} /**
* PUT /books/{id}
* 更新指定ID书籍的信息,
* 需要注意的是,入参Book需要添加注解@RequestBody,才能通过HTTP JSON形式传入
* @param id 希望更新的书籍信息
* @param book 希望更新的书籍信息
*/
@PutMapping("{id}")
public void updateBook(@PathVariable("id") String id, @RequestBody Book book) {
if (book == null || id == null) {
System.out.println("请求数据book为空或指定书籍id为空,终止更新");
return;
}
Optional<Book> first = this.bookList
.stream()
.filter(b -> b.getId().equals(id))
.findFirst();
if (first.isPresent()) {
Book exist = first.get();
exist.setName(book.getName());
exist.setPrice(book.getPrice());
}
} /**
* DELETE /books/{id}
* 根据书籍ID删除对应的书籍信息
* @param id 待删除的书籍ID
*/
@DeleteMapping("{id}")
public void deleteBook(@PathVariable("id") String id) {
if (id == null || id.trim().equals("")) {
return;
}
Optional<Book> existBook = this.bookList
.stream()
.filter(b -> b.getId().equals(id))
.findFirst();
existBook.ifPresent(this.bookList::remove);
}
}

对于该Controller,我们添加了如下的5个API:

  • 获取所有的书籍信息(GET /books)
  • 获取指定ID的书籍信息(GET /books/{id})
  • 增加书籍信息(POST /books)
  • 更新书籍信息(PUT /books/{id})
  • 删除指定ID书籍信息(DELETE /books/{id})

对于URL的定义形式,我们采用了REST ful规范:[RESTful API 一种流行的 API 设计风格](http://www.restfulapi.nl/)。

Web应用启动

最后,我们编写一个启动类启动我们的书籍管理Web服务:

@SpringBootApplication
public class BookManagementSystemApp {
public static void main(String[] args) {
SpringApplication.run(BookManagementSystemApp.class, args);
}
}

功能验证

通过postman等HTTP API工具,我们可以轻松的验证我们的API的正确性。本人也把该处的postman调用文件导出存放在了项目/guide/postman/目录下,同学可以用postman导入使用。

极简SpringBoot指南-Chapter04-基于SpringBoot的书籍管理Web服务的更多相关文章

  1. 黑科技抢先尝(续2) - Windows terminal中Powershell Tab的极简美化指南

    目录 安装python 安装git 安装powerline字体 主题定制 安装oh-my-posh 查看策略组的执行权限 使用choco 安装终端模拟器 - ConEmu 优化 PowerShell ...

  2. 极简SpringBoot指南-Chapter03-基于SpringBoot的Web服务

    仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...

  3. 极简SpringBoot指南-Chapter00-学习SpringBoot前的基本知识

    仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...

  4. 《Springboot极简教程》问题解决:Springboot启动报错 Whitelabel Error Page: This application has no explicit mapping for(转)

    13.2 Spring Boot启动报错:Whitelabel Error Page 13.2 Spring Boot启动报错:Whitelabel Error Page 问题描述 Whitelabe ...

  5. 黑科技抢先尝(续) - Windows terminal中WSL Linux 终端的极简美化指南

    目录 修改默认源,为apt-get安装提速 安装python 和 python pip 安装 zsh 安装powerline-font中的特定字体 安装powerline-shell 修改~目录下的配 ...

  6. 基于Apache axis2开发Java Web服务

    1.安装配置axis2环境 1)下载axis2-1.4.1-war(发布webservice)和axis2-1.4.1-bin.zip(webservice调用使用的各种包) 下载好后把axis2-1 ...

  7. Docker笔记三:基于LVS DR模式构建WEB服务集群

    安装ipvsadm 1. 先在宿主机上安装并以root来启动ipvsadm,每次要在容器中运行ipvs都需要先在宿主机上启动ipvs.如果直接进行2步操作将报出如下错误: Can't initiali ...

  8. 极简SpringBoot指南-Chapter05-SpringBoot中的AOP面向切面编程简介

    仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...

  9. 极简SpringBoot指南-Chapter02-Spring依赖注入的方式

    仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...

随机推荐

  1. ProjectEuler 005题

    题目: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any ...

  2. Spring Boot集成Redis集群(Cluster模式)

    目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...

  3. vue 中this.$on 为什么要放在created中?

    最近在思考一个问题为什么一定要在created中写this.$on,可以放在mounted中吗 如果触发和监听组件在页面上都创建了,那么可以放在mounted中 这种情况在实际工作中比较常见,如果在触 ...

  4. Go依赖包管理--间接依赖

    目录 1.indirect含义 1.2 直接依赖未启用 Go module 1.2 直接依赖 go.mod 文件不完整 2.总结 1.indirect含义 在使用 Go module 过程中,随着引入 ...

  5. SpringSecurity入门

    基础 spring security的底层就是一个过滤器链 ExceptionTranslationFilter是一个异常过滤器,用来处理认证授权过程中的异常 UseranmePasswordAuth ...

  6. MySQL-后知知觉的索引

       什么是索引? 索引在MySQL中也叫做"键",是存储引擎用于快速找到记录的一种数据结构.索引对于良好的性能 非常关键,尤其是当表中的数据量越来越大时,索引对于性能的影响愈发重 ...

  7. Python中的多线程编程

    前言: 线程是操作系统能够进行运算调度的最小单位(程序执行流的最小单元) 它被包含在进程之中,是进程中的实际运作单位 一个进程中可以并发多个线程每条线程并行执行不同的任务 (线程是进程中的一个实体,是 ...

  8. Disable_functions绕过整合

    转载 https://whoamianony.top/2021/03/13/Web安全/Bypass Disable_functions/ https://www.mi1k7ea.com/2019/0 ...

  9. Pytest 系列(28)- 参数化 parametrize + @allure.title() 动态生成标题

    如果你还想从头学起Pytest,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1690628.html 前言 参数化 @pytest.ma ...

  10. 下载excel(接收文件流)

    /**  * 文件流转换 主要代码块,可自定义下载文件名称  * @param {} data  */ export function download(data, titName) {   if ( ...