REST 即表現(xiàn)層狀態(tài)轉(zhuǎn)換(REST,英文:Representational State Transfer). 適合終端到 Server 的調(diào)用。
1 .REST 概述
資源 (Resources )
資源就是網(wǎng)絡(luò)上的一個具體的信息。 可以使用 URI 來映射該資源,因此 URI 是描述唯一資源的標(biāo)識符。表現(xiàn)層 (Representational )
資源是一種信息的載體,資源可以有多種表現(xiàn)形式??梢允褂?請求頭來表示,通常使用的是 后綴來區(qū)分。狀態(tài)轉(zhuǎn)化( State Transfer )
訪問資源的過程中,涉及數(shù)據(jù)狀態(tài)的變化,通過 HTTP 協(xié)議中的請求方法 (GET/POST/PUT/DELETE/PATCH) 來定義操作數(shù)據(jù)狀態(tài)的轉(zhuǎn)化
| HTTP 請求方式 | 含義 |
|---|---|
| POST | 增加資源 |
| PUT | 更改資源,客戶端提供需要提供完整的資源屬性 |
| GET | 查詢資源 |
| PATCH | 更新資源,客戶端提供僅需要的資源屬性 |
| DELETE | 刪除資源 |
| HEAD | 類似 GET ,但僅僅只有 HTTP 頭信息,頭信息包含了需要查找的信息,一般為該資源的元信息,如資源是否存在,長度等 |
| OPTIONS | 用于獲取 URI 所支持的方法,響應(yīng)信息會在 HTTP 頭中包含一個名為 "Allow" 的頭。值是支持的方法,如 GET / POST |
2. Spring Boot 集成 REST 應(yīng)用開發(fā)
- pom 文件配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.zj.sp.rest</groupId>
<artifactId>sp-zj-rest-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sp-zj-rest-demo</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- REST 接口開發(fā)
package org.zj.sp.rest.spzjrestdemo.user.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zj.sp.rest.spzjrestdemo.user.model.UserModel;
import org.zj.sp.rest.spzjrestdemo.user.repository.UserRepository;
@RestController
@RequestMapping(path="/api/v1/user/")
public class UserApiController {
private static final Logger logger = LoggerFactory.getLogger(UserApiController.class);
@Autowired
UserRepository userRepository;
/**
* 查詢用戶列表, 返回 JSON 數(shù)據(jù)
*/
@GetMapping
public List<UserModel> getUsers(){
return userRepository.findAll();
}
/**
* 按 id 查詢用戶, 返回 JSON 數(shù)據(jù)
*/
@GetMapping("{id}")
public UserModel getUser(@PathVariable("id") Long id) {
logger.info("=================" + id);
return userRepository.getOne(id);
}
/**
* 新增用戶
*/
@PostMapping(consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
public void addUser(@RequestBody UserModel model) {
logger.info(model.toString());
userRepository.save(model);
}
/**
* 修改用戶
*/
@PutMapping
public void modifyUser(@RequestBody UserModel model) {
userRepository.save(model);
}
@DeleteMapping("{id}")
public void deleteUser(@PathVariable("id") Long id) {
userRepository.deleteById(id);
}
}
- 配置文件
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://192.168.1.6:3306/testdb?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.show-sql=true
logging.level.root=error
logging.level.org.zj=debug
-
測試結(jié)果
接口測試結(jié)果圖
3. Swagger UI
Swagger UI 是 REST 接口的一個工具,可以使用Swagger UI 來描述和規(guī)范接口
- pom 配置 Swagger UI
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- javaConfig 配置 Swagger
@Bean
public Docket alipayApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("用戶API接口文檔")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("org.zj.sp.rest.spzjrestdemo.user.controller"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用戶服務(wù)")
.description("用戶服務(wù)接口")
.termsOfServiceUrl("http://www.itdecent.cn/u/d775c518e5ba")
.contact(new Contact("聯(lián)系方式 ", "http://www.itdecent.cn/u/d775c518e5ba", "93414020@qq.com"))
.version("1.0").build();
}
- 接口 Swagger 注解配置
package org.zj.sp.rest.spzjrestdemo.user.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zj.sp.rest.spzjrestdemo.user.model.UserModel;
import org.zj.sp.rest.spzjrestdemo.user.repository.UserRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(path="/api/v1/user/")
@Api(tags="用戶接口")
public class UserApiController {
private static final Logger logger = LoggerFactory.getLogger(UserApiController.class);
@Autowired
UserRepository userRepository;
/**
* 查詢用戶列表, 返回 JSON 數(shù)據(jù)
*/
@GetMapping
@ApiOperation(value="查詢用戶列表")
public List<UserModel> getUsers(){
return userRepository.findAll();
}
/**
* 按 id 查詢用戶, 返回 JSON 數(shù)據(jù)
*/
@GetMapping("{id}")
@ApiOperation(value="通過id 查詢用戶")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
public UserModel getUser(@PathVariable("id") Long id) {
logger.info("=================" + id);
return userRepository.getOne(id);
}
/**
* 新增用戶
*/
@PostMapping(consumes=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation(value="新增用戶")
@ApiImplicitParam(name = "model", value = "用戶詳細實體UserModel", required = true, dataType = "UserModel")
public void addUser(@RequestBody UserModel model) {
logger.info(model.toString());
userRepository.save(model);
}
/**
* 修改用戶
*/
@PutMapping
@ApiOperation(value="更新用戶")
@ApiImplicitParam(name = "model", value = "用戶詳細實體UserModel", required = true, dataType = "UserModel")
public void modifyUser(@RequestBody UserModel model) {
userRepository.save(model);
}
@DeleteMapping("{id}")
@ApiOperation(value="通過id 刪除用戶")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
public void deleteUser(@PathVariable("id") Long id) {
userRepository.deleteById(id);
}
}
- swagger 常用注解
@Api:用在類上,說明該類的作用
@ApiOperation:用在方法上,說明方法的作用
@ApiImplicitParams:用在方法上包含一組參數(shù)說明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數(shù)的各個方面
paramType:參數(shù)放在哪個地方
header–>請求參數(shù)的獲?。篅RequestHeader
query–>請求參數(shù)的獲?。篅RequestParam
path(用于restful接口)–>請求參數(shù)的獲?。篅PathVariable
body(不常用)
form(不常用)
name:參數(shù)名
dataType:參數(shù)類型
required:參數(shù)是否必須傳
value:參數(shù)的意思
defaultValue:參數(shù)的默認值
@ApiResponses:用于表示一組響應(yīng)
@ApiResponse:用在@ApiResponses中,一般用于表達一個錯誤的響應(yīng)信息
code:數(shù)字,例如400
message:信息,例如”請求參數(shù)沒填好”
response:拋出異常的類
@ApiModel:描述一個Model的信息(這種一般用在post創(chuàng)建的時候,使用@RequestBody這樣的場景,請求參數(shù)無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModelProperty:描述一個model的屬性
-
swagger 測試圖
測試

