1.RESTful API
1.1相关知识
1.2实现
在controller文件夹下建立UserController.java:
package com.example.helloworld.controller; import com.example.helloworld.entity.User; import org.springframework.web.bind.annotation.*; @RestController public class UserController { @GetMapping("/user/{id}") public String getUserById(@PathVariable int id) { //@PathVariable 注解配合 @GetMapping("/user/{id}") 中的{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删除用户"; } }
1.3 测试
进入/user/10:
IDEA里返回了user的id:10,并且LoginInterceptor为上一节课写的拦截器,拦截了/user/
2.Swagger
1.相关知识
2.2 实现
2.2.1 在pom.xml下添加如下依赖
<!--添加swagger2相关功能 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!--添加swagger-ui相关功能 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
2.2.3 在config文件夹下创建WebConfig.java
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")) //com包下的所有api都交给swagger管理 .paths(PathSelectors.any()) .build(); } /** * 创建该API的基本信息(这些基本信息会展现在文档页面中) * 访问地址:http://项目实际地址/swagger-ui.html * * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2") .description("") .version("1.0") .build(); } }
2.3测试