第3章 使用Spring MVC开发RESTful API

Restful简介

第一印象

左侧是传统写法,右侧是RESTful写法

  1. 用url描述资源,而不是行为

  2. 用http方法描述行为,使用http状态码来表示不同的结果(200表示成功,500表示错误)

  3. 使用json交互数据

  4. RESTful只是一种风格,并不是强制的标准

REST成熟度模型

编写第一个Restful API

通过用户查询,创建,删除,修改来学习怎么写一个Restful API

编写针对RestfullAPI的测试用例

UserController.java

@RestController
@RequestMapping("user")
public class UserController { private List<User> getThreeEmptyUsers() {
List<User> userList = new ArrayList<>();
userList.add(new User());
userList.add(new User());
userList.add(new User());
return userList;
} @RequestMapping(value = "query1", method = RequestMethod.GET)
public List<User> query() {
return getThreeEmptyUsers();
}
}

UserControllerTest.java

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private WebApplicationContext context; private MockMvc mockMvc; @Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
} @Test
public void whenQuerySuccess() throws Exception {
mockMvc.perform(get("/user/query1")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk()) // 返回状态码为200
.andExpect(jsonPath("$.length()").value(3)); // 返回数据的集合长度是3
}
}

jsonPath表达式

常用注解

@RestControlelr 标明此Controller提供RestAPI

@RequestMapping及其变体,映射http请求url到java方法

@RequestParam 映射请求参数到Java方法的参数

@PageableDefault 指定分页参数的默认值

@JsonView 控制json输出内容,使用步骤如下

  • 使用接口来声明多个视图
  • 在值对象的get方法上指定视图
  • 在Controller方法上指定视图

@GetMapping @RequestMapping的变体

传递参数

@PathVariable 映射url片段到java方法的参数 用户详情服务

  • 在url声明中使用正则表达式

@RequestBody 映射请求体到java方法的参数

日期类型参数的处理

  • 传递时间戳,有利于前后台分离

@Valid注解和BindingResult验证请求参数的合法性并处理校验结果

参数校验

常用的验证注解

自定义消息

  • message = ""

自定义校验注解

  • 参照代码的MyConstraint

服务异常处理

工具:chrome插件Restlet Client测试Restful接口的插件

Spring Boot中默认的错误处理机制

分析源码:BasicErrorController

如果请求一个不存在的url,app发出的请求返回json格式,浏览器发出的请求返回 页面格式。

依据Content-Type来判断是请求的页面还是json

自定义异常处理

text/html 基于状态码处理

  • 配置404 resources/resources/error/404.html

application/json

  • 参照代码UserNotExistException

拦截REST服务

Filter 过滤器

自定义过滤器,TimeFilter,加Component注释

第三方过滤器,LogFilter,通过WebConfig添加

拿不到Controller方法

Interceptor 拦截器

TimeInterceptor

拿不到Controller方法的参数

分析源码:DispatcherServlet/doService/doDispatcher/ha.handle(参数的拼装是调用这个方法完成的)

Aspect 切片

when/where/do what

关系

使用REST方式处理文件服务

测试方法

@Test
public void whenUploadSuccess() throws Exception{
String result = mockMvc.perform(fileUpload("/file")
.file(new MockMultipartFile("file", "text.txt", "multipart/form-data", "hello update".getBytes("UTF-8"))))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}

文件上传下载

@RestController
@RequestMapping("file")
public class FileController {
@PostMapping
public FileInfo upload(MultipartFile file) throws Exception { System.out.println("name: " + file.getName());
System.out.println("filename: " + file.getOriginalFilename());
String filePath = System.getProperty("user.home") + File.separator + new Date().getTime() + ".txt";
File localFile = new File(filePath);
file.transferTo(localFile); return new FileInfo(filePath);
} @GetMapping("{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
String filePath = System.getProperty("user.home") + File.separator + id + ".txt";
File file = new File(filePath);
if (!file.exists()) {
System.out.println("文件不存在");
return;
}
try (
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
) {
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename=test.txt"); IOUtils.copy(is, os);
os.flush();
}
}
}

使用Spring MVC开发RESTful API的更多相关文章

  1. 使用Spring MVC开发RESTful API(续)

    使用多线程提高REST服务性能 异步处理REST服务,提高服务器吞吐量 使用Runnable异步处理Rest服务 AsyncController.java @RestController @GetMa ...

  2. Spring Boot开发RESTful接⼝服务及单元测试

    Spring Boot开发RESTful接⼝服务及单元测试 常用注解解释说明: @Controller :修饰class,⽤来创建处理http请求的对象 @RestController :Spring ...

  3. ASP.NET Core Web API 开发-RESTful API实现

    ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...

  4. 应用Spring MVC发布restful服务是怎样的一种体验

            摘要:“约定优于配置”这是一个相当棒的经验,SOAP服务性能差.基于配置.紧耦合,restful服务性能好.基于约定.松耦合,现在我就把使用Spring MVC发布restful服务的 ...

  5. 用Spring MVC开发简单的Web应用

    这个例子是来自于Gary Mak等人写的Spring攻略(第二版)第八章Spring @MVC中的一个例子,在此以学习为目的进行记录. 问题:想用Spring MVC开发一个简单的Web应用, 学习这 ...

  6. flask开发restful api系列(8)-再谈项目结构

    上一章,我们讲到,怎么用蓝图建造一个好的项目,今天我们继续深入.上一章中,我们所有的接口都写在view.py中,如果几十个,还稍微好管理一点,假如上百个,上千个,怎么找?所有接口堆在一起就显得杂乱无章 ...

  7. flask开发restful api

    flask开发restful api 如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restfu ...

  8. 使用Spring boot开发RestFul 风格项目PUT/DELETE方法不起作用

    在使用Spring boot 开发restful 风格的项目,put.delete方法不起作用,解决办法. 实体类Student @Data public class Student { privat ...

  9. 描述怎样通过flask+redis+sqlalchemy等工具,开发restful api

    flask开发restful api系列(8)-再谈项目结构 摘要: 进一步介绍flask的项目结构,使整个项目结构一目了然.阅读全文 posted @ 2016-06-06 13:54 月儿弯弯02 ...

随机推荐

  1. Java根路径设置(在获取本地路径时会获取到这个文件夹,,这样就可以专门放配置文件了)

    在获取本地路径时会获取到这个文件夹,,这样就可以专门放配置文件了

  2. css3 nth-child选择器

    css3 nth-child选择器 css3的nth-child选择器,乍看起来很简单,其实不是那么容易. 简单用法 p:nth-child(n) // 选择属于其父元素的第n个子元素的每个 < ...

  3. 在 Mac 上开发 .NET MAUI

    .NET 多平台应用程序 UI (.NET MAUI) 是一个跨平台框架,用于使用 C# 和 XAML 创建本机移动和桌面应用程序,这些应用程序可以从单个共享代码库在 Android.iOS.macO ...

  4. [ Linux ] 设置服务器开机自启端口

    https://www.cnblogs.com/yeungchie/ 需要用到的工具: crontab iptables crontab.set SHELL=/bin/bash PATH=/sbin: ...

  5. msyql查看版本号、最大连接数、当前连接数等

    1.查看版本号 select version(); 2.查看最大连接数 show variables like 'max_connections'; 3.查看当前连接数(如果是root帐号,你能看到所 ...

  6. 羽夏壳世界—— PE 结构(上)

    羽夏壳世界之 PE 结构(上),介绍难度较低的基本 PE 相关结构体.

  7. golang-grpc

    目录 1. 什么是grpc和protobuf 1.1 grpc 1.2 protobuf 2.go下grpc 2.1官网下载protobuf工具 2.2 下载go的依赖包 2.3 编写proto文件 ...

  8. js 递归求1/2+1/4+1/6+....1/n的和,和1/1+1/3+1/5+.....+1/n的和

        function fun1(n) {         if (n == 2) {             return 1 / 2;         } if (n == 1) {       ...

  9. Codeforces Round #706 (Div. 2)B. Max and Mex __ 思维, 模拟

    传送门 https://codeforces.com/contest/1496/problem/B 题目 Example input 5 4 1 0 1 3 4 3 1 0 1 4 3 0 0 1 4 ...

  10. 2021.07.19 P2294 狡猾的商人(差分约束)

    2021.07.19 P2294 狡猾的商人(差分约束) [P2294 HNOI2005]狡猾的商人 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 重点: 1.差分约束最长路与最短 ...