第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. 理解feof与EOF

    feof(feof msdn) feof用于判断文件结尾.头文件<cstdio>.使用方法是feof(fp),fp为指向需要判断的文件的指针.如果不到文件结尾,返回0值:如果是文件结尾,返 ...

  2. 印度下架54款中国APP,中东政策逐年收紧,伊拉克成蓝海市场

    2月14日,印度电子和信息技术部以"安全威胁"为由对有中国基因的54款App下达禁令,15日,印度税务部门对某些在印中资企业多个场所进行搜查. 本批下架的App中主要以应用类App ...

  3. Amaze UI 模版中心上线丨十几款高质量优秀模版免费提供!

    Amaze UI模版中心终于上线了,目前汇聚了包含企业门户.新闻资讯.管理后台等多个领域的模版,全都可以免费下载. Amaze UI模版中心后续还会增加更多的模版以及领域,请各位持续关注. 模版中心的 ...

  4. the compatibility problem of ie

    ie8hack ie8下的兼容问题处理:背景透明,css3圆角,css3和jquery支持部分css3选择器(例如:nth-child),支持html5的语义化标签,媒体查询@media等. 在htm ...

  5. 饿了么组件库element-ui正则表达式验证表单,后端验证表单。

    前言 老是遇到一些朋友问一些element-ui组件使用相关的基础问题,因为官方文档上并没有提供所有琐碎的功能代码demo.从这里开始我会根据我实际遇到的问题记录一些常见的官方文档没有详述的功能代码, ...

  6. ubantu系统之 lunch时报错:no such file /....../.lunchrc

    no such file /....../.lunchrc 出现时: 使用 source build/envsetup.sh 执行完后 再用lunch

  7. jboss修改内存

    在修改配置文件,在 <JBOSS_HOME> /bin/stadalone.conf中      找到并修改  如图

  8. SQL注入之延迟盲注

    延迟盲注 你不知道你输入的数据在sql被执行后是否是正确或错误的.你只知道有数据. 利用原理 借助if语句,如果正确就sleep(5),延迟5秒返回数据.通过数据返回的时间大小判断自己的语句是否正确执 ...

  9. Spring Boot-自动配置之底层原理

    一.SpringBoot启动的时候加载主配置类,开启了自动配置的功能 @SpringBootApplication public class SpringBoot02Application { pub ...

  10. Spring5-IOC底层原理

    1.什么是IOC (1)控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理 (2)使用IOC目的:为了降低耦合度 2.IOC底层原理 (1)xml解析.工厂模式.反射