六、 Spring Boot 之 REST

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 測試圖


    測試

源碼下載 :

https://github.com/cqzhangjian/SpringBoot-REST.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一說到REST,我想大家的第一反應(yīng)就是“啊,就是那種前后臺通信方式?!钡窃谝笤敿氈v述它所提出的各個約束,以及如...
    時待吾閱讀 3,602評論 0 19
  • 本文屬于原創(chuàng),轉(zhuǎn)載注明出處,歡迎關(guān)注微信小程序小白AI博客 微信公眾號小白AI或者網(wǎng)站 https://xiaob...
    小白AI閱讀 648評論 0 4
  • 概述 微服務(wù)所使用的協(xié)議自然要根據(jù)服務(wù)的特點和類型來選擇 這里說的協(xié)議主要是指應(yīng)用層協(xié)議, 傳輸層協(xié)議一般都是TC...
    老瓦在霸都閱讀 7,775評論 0 7
  • 第2章 API文檔與模擬數(shù)據(jù)接口 學(xué)習(xí)目標(biāo): 理解RESTful架構(gòu) 運用Swagger編寫API文檔 掌握Moc...
    key168863閱讀 1,062評論 0 1
  • 讓·皮亞杰 讓·皮亞杰(Jean Piaget,1896—1980),瑞士心理學(xué)家,發(fā)生認識論創(chuàng)始人。他先是一位生...
    博苑云飛閱讀 1,434評論 0 1

友情鏈接更多精彩內(nèi)容