睁眼写BUG,闭眼改BUG。

构建 RESTful 服务

2019.06.30

构建 RESTful 服务

REST (Representational State Transfer)是一种 Web 软件架构风格,它是一种风格,而不是标 准,匹配或兼容这种架构风格的网络服务称为REST 服务。REST 服务简洁并且有层次,REST 通 常基于 HTTP、 URI 和 XML 以及 HTML 这些现有的广泛流行的协议和标准。在 REST 中,资源是 由 URI 来指定的,对资源的增删改查操作可以通过 HTTP 协议提供的 GET、 POST、 PUT、 DELETE 等方法实现。使用REST 可以更高效地利用缓存来提高响应速度, 同时 REST 中的通信会话状态由 客户端来维护,这可以让不同的服务器处理一系列请求中的不同请求,进而提高服务器的扩展性。 在前后端分离项目中, 一个设计良好的 Web 软件架构必然要满足 REST 风格。 在 Spring MVC 框架中,开发者可以通过@RestController 注解开发一个RESTful 服务,不过, Spring Boot 对此提供了自动化配置方案,开发者只需要添加相关依赖就能快速构建一个RESTful 服务。

JPA 实现 REST

引入依赖

        <!-- JPA -->
        <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>

        <!-- Restful -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

数据源正常配置即可

案列

Test.java

@Data
@Entity
@Table(name = "test")
public class Test implements Serializable {
    /**
     * 测试
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

}

实体类中使用了lombox插件

TestRepository.java

/**
 * 测试持久层
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/29
 * @Description: work.idler.dtai.repository
 * @version: 1.0
 */
public interface TestRepository extends JpaRepository<Test, Long> {
}

利用postman等工具访问以下接口即可

功能接口请求方式
查询全部http: //localhost : 8080/testsGET
按id查http: //localhost : 8080/tests/1GET
分页查http: //localhost : 8080/tests?page=1&size=20GET
分页并倒序查http: //localhost : 8080/tests?page=1&size=20&sort=id,descGET
修改http: //localhost : 8080/tests/2PUT
删除http: //localhost : 8080/tests/2DELETE
添加http: //localhost : 8080/testsPOST
.........

其他配置

#每页默认记录数,默认值为 20 
spring.data.rest.default-page-size=2 
#分页查询页码参数名,默认值为 page 
spring.data.rest.page-param-name=page 
#分页查询记录数参数名,默认值为 size
spring.data.rest.limit-param-name=size 
#分页查询排序参数名, 默认值为 sort 
spring.data.rest.sort-param-name=sort 
#base-path 表示给所有请求路径都加上前缀 
spring.data.rest.base-path=/api
#添加成功时是否返回添加内容 
spring.data.rest.return-body-on-create=true 
#更新成功时是否返回更新内容 
spring.data.rest.return-body-on-update=true 

同样, 这些配置可以在java代码、xml、yml 中配置, java代码中配置优先级最高

MongoDB 实现REST

除了引入mongo的starter, 数据连接配置不一样, 其他同理, easy

更多参考书籍

  • Spring Boot + vue 全栈开发实战