极简SpringBoot指南-Chapter04-基于SpringBoot的书籍管理Web服务
仓库地址
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服务的更多相关文章
- 黑科技抢先尝(续2) - Windows terminal中Powershell Tab的极简美化指南
目录 安装python 安装git 安装powerline字体 主题定制 安装oh-my-posh 查看策略组的执行权限 使用choco 安装终端模拟器 - ConEmu 优化 PowerShell ...
- 极简SpringBoot指南-Chapter03-基于SpringBoot的Web服务
仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...
- 极简SpringBoot指南-Chapter00-学习SpringBoot前的基本知识
仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...
- 《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 ...
- 黑科技抢先尝(续) - Windows terminal中WSL Linux 终端的极简美化指南
目录 修改默认源,为apt-get安装提速 安装python 和 python pip 安装 zsh 安装powerline-font中的特定字体 安装powerline-shell 修改~目录下的配 ...
- 基于Apache axis2开发Java Web服务
1.安装配置axis2环境 1)下载axis2-1.4.1-war(发布webservice)和axis2-1.4.1-bin.zip(webservice调用使用的各种包) 下载好后把axis2-1 ...
- Docker笔记三:基于LVS DR模式构建WEB服务集群
安装ipvsadm 1. 先在宿主机上安装并以root来启动ipvsadm,每次要在容器中运行ipvs都需要先在宿主机上启动ipvs.如果直接进行2步操作将报出如下错误: Can't initiali ...
- 极简SpringBoot指南-Chapter05-SpringBoot中的AOP面向切面编程简介
仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...
- 极简SpringBoot指南-Chapter02-Spring依赖注入的方式
仓库地址 w4ngzhen/springboot-simple-guide: This is a project that guides SpringBoot users to get started ...
随机推荐
- 分布式链路追踪系统Sleuth和ZipKin
1.微服务下的链路追踪讲解和重要性 简介:讲解什么是分布式链路追踪系统,及使用好处 进行日志埋点,各微服务追踪. 2.SpringCloud的链路追踪组件Sleuth 1.官方文档 http://cl ...
- 改变this指向&闭包特性
Q:为什么用普通函数时,setTimeout里面的this指向的是window? //通过保留this的方式,通过闭包的特性去拿this let _this = this //...ajax setT ...
- 面试官问我MySQL索引,我
面试官:我看你简历上写了MySQL,对MySQL InnoDB引擎的索引了解吗? 候选者:嗯啊,使用索引可以加快查询速度,其实上就是将无序的数据变成有序(有序就能加快检索速度) 候选者:在InnoDB ...
- 微信支付 调用支付jsapi缺少参数total_fee 和 支付验证签名失败 prepay_id配置问题
=======================================================先熟悉一下统一下单api所需要的参数=========================== ...
- K8s 系列(四) - 浅谈 Informer
1. 概述 进入 K8s 的世界,会发现有很多的 Controller,它们都是为了完成某类资源(如 pod 是通过 DeploymentController, ReplicaSetControlle ...
- Appium自动化(3) - adb无线连接手机的方法
如果你还想从头学起Appium,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1693896.html 前言 除了USB方式连接Andro ...
- 解决CSDN文章下载后,依然请求跳转至首页出错的问题
1. 搜索关键字:"onerror" 然后找到如下所示代码: <div style="display:none;"> <img ...
- MacOS隐藏及显示文件
显示隐藏文件 显示所有文件 defaults write com.apple.finder AppleShowAllFiles -boolean true killall Finder 不显示隐藏 ...
- C# Dapper基本三层架构使用 (三、BLL)
BLL层介绍 业务逻辑层用于做一些有效性验证的工作,以更好的保证程序运行的健壮性.如完成数据添加.修改和查询业务等:不允许指定的文本框中输入空字符串,数据格式是否正确以及数据类型验证:用户权限的合法性 ...
- VUE005. 在data中使用 / 改变data,或在data中调用method函数
使用三方UI库时经常会遇到在data中写入方法的场景,如Element-UI的级联选择器(动态加载part)需要在data中写入lazyLoad. 但后端总会给出意想不到的需求: 通过接口调取一串数据 ...