目录
1.RESTfuI服务
1.RESTfUI介绍
1.RESTfuI是目前流行的互联网软件服务架构设计风格。
2.REST并不是一个标准,它更像一组客户端和服务端交互时的架构理念和设计原则,基于这种架构理念和设计原则的Web API更加简洁,更有层次。
2.RESTful的特点
1.每一个URI代表一种资源
2.客户端使用GET、POST、PUT、DELETE四种表示操作方式的动词对服务端资源进行操作:GET用于获取资源,POST用于新建资源(也可以用于更新资源)PUT用于更新资源,DELETE用于删除资源。
3.通过操作资源的表现形式来实现服务端请求操作。
4.资源的表现形式是JSON或者HTML。
5.客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都包含必需的信息。
3.Spring Boot实现RESTfUI API
1.Spring Boot提供的spring-boot-starter-web组件完全支持开发RESTfuI API提供了与REST操作方式(GET、POST、PUT、DELETE)对应的注解。
2.@GetMapping:处理GET请求,获取资源.
3.@PostMapping:处理POST请求,新增资源。
4.@PutMapping:处理PUT请求,更新资源。
5.@DeleteMapping:处理DELETE请求,删除资源。
6.@PatchMapping:处理PATCH请求,用于部分更新资源。
2.Swagger
pom.xml加入Swagger两个依赖
Spring Boot 2.6.X后与Swagger有版本冲突问题,需要在application.properties中加入以下配置:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
config包下面新建SwaggerConfig类
package com.example.helloworld.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("演示项目API")// 标题
.description("演示项目")// 描述
.version("1.0")// 版本
.build();
}
}
controller包下新建UserController类
package com.example.helloworld.controller;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import com.example.helloworld.entity.User;
@RestController
public class UserController {
@ApiOperation("获取用户")
@GetMapping("/user/{id}")
public String getUserById(@PathVariable int id){
System.out.println(id);
return"根据ID获取用户信息";
}
@PostMapping("/user")
public String save(User user){return"添加用户";}
@PutMapping("/user")
public String update(User user){ return"更新用户";}
@DeleteMapping("/user/{id}")
public String deleteById(@PathVariable int id){
System.out.println(id);
return"根据ID删除用户";
}
}
运行,浏览器http://127.0.0.1:8080/swagger-ui.htm
使用之前写的文件上传