SpringBoot学习散记(二)
一. RESTful API
-
首先 啥是 RESTful API?
要弄清楚什么是RESTful API,首先要弄清楚什么是REST。REST – REpresentational State Transfer,英语的直译就是“表现层状态转移”。如果看这个概念,估计没几个人能明白是什么意思。那下面就让我来用一句人话解释一下什么是RESTful:URL定位资源,用HTTP动词(GET,POST,PUT,DELETE)描述操作。Resource:资源,即数据。
Representational:某种表现形式,比如用JSON,XML,JPEG等;
State Transfer:状态变化。通过HTTP动词实现。所以RESTful API就是REST风格的API。 那么在什么场景下使用RESTful API呢?在当今的互联网应用的前端展示媒介很丰富。有手机、有平板电脑还有PC以及其他的展示媒介。那么这些前端接收到的用户请求统一由一个后台来处理并返回给不同的前端肯定是最科学和最经济的方式,RESTful API就是一套协议来规范多种形式的前端和同一个后台的交互方式。
详情请看 https://blog.csdn.net/hjc1984117/article/details/77334616 -
RESTful API 的实现
首先创建一个 User 的entity
public class User {
private Long id;
private String name;
private Integer age;
//省略Get和Set方法 自己加一下
创建一个Controller
@RestController
@RequestMapping("/user")
public class UserController {
// 创建线程安全的Map
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@GetMapping("getUserList")
@ApiOperation(value = "获取用户列表",notes = "查看所用用户列表")
public List<User> getUserList() {
// 处理"/users/"的GET请求,用来获取用户列表
// 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value = "新增用户" ,notes = "用户注册提交到此保存")
@RequestMapping(value = "/", method = RequestMethod.POST)
public String postUser(@ModelAttribute User user) {
// 处理"/users/"的POST请求,用来创建User
// 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value = "用户信息查询",notes = "根据ID查询用户信息")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id) {
// 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
// url中的id可通过@PathVariable绑定到函数的参数中
return users.get(id);
}
@ApiOperation(value = "编辑用户信息", notes = "修改用户的信息")
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@ApiOperation(value = "删除用户",notes = "注销账户")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
// 处理"/users/{id}"的DELETE请求,用来删除User
users.remove(id);
return "success";
}
大家可以发现 这 增 删 改 查 四个接口 的请求路径都是 IP+端口+项目名+/user
而通过不同的 Http方式 post是增 delete是删 put是改 get是查 好似每一种请求方式 对应一个动词
- 参数的传递
关于RESTful API参数的传递如下
@ApiOperation(value = "用户信息查询",notes = "根据ID查询用户信息")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id) {
// 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
// url中的id可通过@PathVariable绑定到函数的参数中
return users.get(id);
}
@RequestMapping(value = “/{id}”, method = RequestMethod.GET) 中申明了
/{id} 请求路径后的 第一个参数 是 id
在接口参数列表中 我们使用 @PathVariable 来获取到 id 这个属性
@ApiOperation(value = "编辑用户信息", notes = "修改用户的信息")
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@RequestMapping(value = “/{id}”, method = RequestMethod.PUT)
public String putUser(@PathVariable Long id, @ModelAttribute User user) {
除了 @RequestMapping(value = “/{id}”, 申明的id参数以外.像age,name这样的参数 依旧可以向SSM框架一样 用entity接收
二. Swagger2
- 首先什么是Swagger2
Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。 - 在pom.xml 导入jar包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
- 编写Swagger2 类
在StudentApplication.java 所在的同级目录创建Swagger2.java类
package com.springboot.student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
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 Swagger2 extends WebMvcConfigurerAdapter {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.springboot.student.web"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("自动构建接口文档")
.termsOfServiceUrl("***")
.contact("小杨同学...")
.version("1.0")
.build();
}
}
并在控制器每个接口上面 使用 @ApiOperation()注解对接口进行说明和描述
@ApiOperation(value = "新增用户" ,notes = "用户注册提交到此保存")
@RequestMapping(value = "/", method = RequestMethod.POST)
public String postUser(@ModelAttribute User user) {
// 处理"/users/"的POST请求,用来创建User
// 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
users.put(user.getId(), user);
return "success";
}
编写好之后 重启项目 使用 http://localhost/swagger-ui.html 访问 我这里使用的是80端口 大家把端口号带上
如果有童鞋出现了 404的情况 请检查一下 自己的 spring.mvc.static-path-pattern 是否是 /** 如果不是的话 请在 Swagger2中重写 addResourceHandlers 方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
再次请求尝试