一、Restful
1.什么是Restful?
REST指的是一組架構約束條件和原則。REST並沒有一個明確的標准,而更像是一種設計的風格。 如果一個架構符合REST的約束條件和原則,我們就稱它為RESTful架構。
2.Restful的特點(摘自:百度百科)
- 每一個URI代表1種資源;
- 客戶端使用GET、POST、PUT、DELETE4個表示操作方式的動詞對服務端資源進行操作:GET用來獲取資源,POST用來新建資源(也可以用於更新資源),PUT用來更新資源,DELETE用來刪除資源;
- 通過操作資源的表現形式來操作資源;
- 資源的表現形式是XML或者HTML;
- 客戶端與服務端之間的交互在請求之間是無狀態的,從客戶端到服務端的每個請求都必須包含理解請求所必需的信息。
3.Restful的風格
@RequestMapping(value = "selectOne/{id}",method = RequestMethod.GET) @ResponseBody public String selectOne(@PathVariable Integer id) { return JSON.toJSONString(this.infoService.queryById(id)); }
Ps:
1.這里需要注意的是@RequestMapping注解參數以{}傳遞,還要明確請求的方法,使用@PathVariable注解綁定參數(多個參數需要綁定參數名)。
2.支持Restful風格的注解@PutMapping、@GetMapping、@DeleteMapping、@PostMapping
二、swagger的使用
1.添加swagger依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.配置swagger
@Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Spring Boot 使用Swagger2構建API文檔") .description("Restful風格的API") .version("1.0") .build(); } }
3.給需要產生接口文檔的接口添加說明信息
@ApiOperation(value = "查詢數據",notes = "根據主鍵查詢單條數據")
@ApiImplicitParam(name = "id",value = "id",required = true,paramType = "path",dataType = "Long")
@RequestMapping(value = "selectOne/{id}",method = RequestMethod.GET)
@ResponseBody
public String selectOne(@PathVariable Integer id) {
return JSON.toJSONString(this.infoService.queryById(id));
}
4.重啟項目,在地址欄中輸入:http://localhost:8080/swagger-ui.html


5.swagger的補充
在使用swagger的時候可能會出現404錯誤,下面提供一種解決方案(需要視具體情況而定,有可能解決你的問題)
@Configuration public class WebMvcConfig implements WebMvcConfigurer { public void addResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); } }
Ps:在SpringBoot2x和Spring5x后的,有兩種解決方案
1.實現WebMvcConfigurer 接口
2.繼承WebMvcConfigurationSupport
