当前位置:网站首页>JSD - 2204 - Knife4j framework - processing - Day07 response results
JSD - 2204 - Knife4j framework - processing - Day07 response results
2022-08-01 21:05:00 【Program the ape Monkey】
1.Knife4j框架
Knife4j框架是一款基于Swagger 2框架的、Based on the project controller code to generate onlineAPI文档的框架,另外,The framework and debugging,You can ask the server sends a request,并获取响应结果.
About the framework,To make it to be able to use,需要:
- 添加依赖
- 添加配置类
- 在
application.properties中添加1条配置
About dependent code:
<!-- Knife4j Spring Boot:在线API -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
About the configuration class:
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
/**
* Knife4j配置类
*
* @author [email protected]
* @version 0.0.1
*/
@Slf4j
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
/**
* 【重要】指定Controller包路径
*/
private String basePackage = "cn.tedu.csmall.product.controller";
/**
* 分组名称
*/
private String groupName = "product";
/**
* 主机名
*/
private String host = "http://java.tedu.cn";
/**
* 标题
*/
private String title = "Cool shark online mallAPI文档--商品管理";
/**
* 简介
*/
private String description = "Cool shark online mallAPI文档--商品管理";
/**
* 服务条款URL
*/
private String termsOfServiceUrl = "http://www.apache.org/licenses/LICENSE-2.0";
/**
* 联系人
*/
private String contactName = "Java教学研发部";
/**
* 联系网址
*/
private String contactUrl = "http://java.tedu.cn";
/**
* 联系邮箱
*/
private String contactEmail = "[email protected]";
/**
* 版本号
*/
private String version = "1.0.0";
@Autowired
private OpenApiExtensionResolver openApiExtensionResolver;
public Knife4jConfiguration() {
log.debug("加载配置类:Knife4jConfiguration");
}
@Bean
public Docket docket() {
String groupName = "1.0.0";
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.host(host)
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build()
.extensions(openApiExtensionResolver.buildExtensions(groupName));
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.termsOfServiceUrl(termsOfServiceUrl)
.contact(new Contact(contactName, contactUrl, contactEmail))
.version(version)
.build();
}
}
关于application.properties中的配置:
# 开启Knife4jFramework of the enhanced mode
knife4j.enable=true
注意:
- 当前项目的Spring Boot版本必须是2.6以下的版本(2.6不可用)
- If you want to use a higher version of theSpring Boot,Must use a higher version of theKnife4j
- 在配置类中的
basePackageMust be a controller class in the package,Remember that need to be modified
完成后,启动项目,通过 /doc.html Can access onlineAPI文档.
在开发实践中,It should also be on onlineAPIDocument refinement,Need some configuration in the controller and related classes:
- 在控制器类上添加
@Api注解,配置tags属性,此属性是String类型的 - In the controller class process the request method to add
@ApiOperation注解,配置value属性,此属性是String类型的 - In the controller class process the request method to add
@ApiOperationSupport注解,配置order属性,此属性是int类型的- This property is used to sort,Data as the front,不建议使用1位的数字
- In the controller class process the request method,Don't use no limit request
@RequestMapping,建议使用@GetMapping或@PostMapping - If the request is processed method,If the parameter is encapsulated data type,Should be in this type of each attribute to add
@ApiModelProperty注解,To configure the parameters of - If the request is processed method,If the parameter is not encapsulated,则需要使用
@ApiImplicitParams和@ApiImplicitParam这2A combined annotations to configure- 注意:一旦配置了
@ApiImplicitParam,Originally the prompt value will be overwritten,Should complete the configuration of the various properties
- 注意:一旦配置了
Complete the configuration of the sample--AlbumController:
@Api(tags = "04. Photo album management module")
@Slf4j
@RestController
@RequestMapping("/albums")
public class AlbumController {
@Autowired
private IAlbumService albumService;
public AlbumController() {
log.info("创建控制器:AlbumController");
}
// 添加相册
// http://localhost:9080/albums/add-new?name=XiaoMi&description=TestDescription&sort=69
@ApiOperation("添加相册")
@ApiOperationSupport(order = 100)
@PostMapping("/add-new")
public String addNew(@Validated AlbumAddNewDTO albumAddNewDTO) {
log.debug("开始处理【添加相册】的请求:{}", albumAddNewDTO);
albumService.addNew(albumAddNewDTO);
return "Add album success!";
}
// http://localhost:9080/albums/9527/delete
@ApiOperation("根据id删除相册")
@ApiOperationSupport(order = 200)
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "相册id", dataType = "long", required = true)
})
@PostMapping("/{id:[0-9]+}/delete")
public String delete(@PathVariable Long id) {
log.debug("开始处理【删除相册】的请求:id={}", id);
albumService.deleteById(id);
return "Delete album success!";
}
}
Complete the configuration of the sample--AlbumAddNewDTO:
@Data
public class AlbumAddNewDTO implements Serializable {
/**
* 相册名称
*/
@ApiModelProperty(value = "相册名称", example = "小米80的相册", required = true)
@NotNull(message = "必须提交相册名称!")
private String name;
/**
* 相册简介
*/
@ApiModelProperty(value = "相册简介", example = "小米80Introduction to the album", required = true)
@NotNull(message = "Must submit photo album profile!")
private String description;
/**
* 自定义排序序号
*/
@ApiModelProperty(value = "自定义排序序号", example = "88", required = true)
@NotNull(message = "Must submit a custom sorting sequence number!")
@Range(max = 99, message = "Custom order number must be0~99之间的值!")
private Integer sort;
}
2.About the response
When the server response data to the client,In addition to the necessary tooltip text,It should also be response“业务状态码”到客户端,In order to facilitate the client program is convenient and accurate judgment of the current request execution result!
另外,Some operations require data to the client response
所以,To the client's response data needs to include at least the following parts:
- 业务状态码:本质上是一个数值,Agreed jointly by the server and the client the meaning of each numerical
- The descriptive text for the business execution when something goes wrong
- 数据:When the request is processed success,May need to respond to certain data to the client(Usually the client aGET请求,当然,某些POSTThe request may also need to response data)
And it should be for all the requests are such a response,通常,A certain type will custom,用于封装以上3种数据,作为处理请求的方法的返回值类型,当响应时,Spring MVCFramework will return values intoJSON格式的字符串!
提示:Spring MVCAble to handle the request method return value intoJSON格式的字符串,需要:
- This method's response body
- This project needs to be added
jackson-databind依赖
- 在Spring Boot中,
spring-boot-starter-webContains the rely on- This method return value type inSpring MVC中没有默认的Converter(转换器),会自动调用
jackson-databind中的Converter,而jackson-databindThe processing method is to convert the return value toJSON格式的字符串
- As long as it is the custom data types,在Spring MVCNo defaultConverter
例如,在项目的根包下创建web.JsonResult类:
@Data
public class JsonResult implements Serializable {
private Integer state;
private String message;
private Object data;
}
以上类型,Will serve as a project in each processing request method、Each processing methods of abnormal return value type!
如果在ServiceLayer always throwServiceException,Due to the use of the unified exception handling mechanism,All can lead to abnormal business status code is the same!为了解决此问题,可以:
- Create multiple exception types,According to different error,在ServiceThrow out different layer of abnormal
- 在ServiceLayer every time throws an exception,The exception object encapsulates the business status code
If you take more2种做法,则需要将ServiceException调整为:
@Getter
public class ServiceException extends RuntimeException {
private Integer state;
public ServiceException(Integer state, String message) {
super(message);
this.state = state;
}
}
然后,In addition a custom interface,Used to declare constants of each business status code:
public interface ServiceCode {
Integer ERR_CONFLICT = 2;
Integer ERR_NOT_FOUND = 6;
Integer ERR_INSERT = 3;
Integer ERR_UPDATE = 4;
Integer ERR_DELETE = 5;
}
并且,在抛出异常时,The exception object encapsulates the above business status code,例如:
String message = "添加相册失败!相册名称【" + name + "】已存在!";
log.warn(message);
throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
this.axios.post(url, data).then(() => {
let data = response.data;
if (data.state == 1) {
// 成功
} else if (data.state == 2) {
// 显示 data.message
}
});边栏推荐
- 对C语言结构体内存对齐的理解
- AQS原理和介绍
- 如何用Chrome编辑以及调试代码
- Goroutine Leaks - The Forgotten Sender
- JS提升:手写发布订阅者模式(小白篇)
- StringTable详解 串池 性能调优 字符串拼接
- Based on FPGA in any number of bytes (single-byte or multibyte) serial port (UART) to send (including source engineering)
- system collection
- 织梦发布文章提示body has not allow words错误
- 通俗解释:什么是临床预测模型
猜你喜欢
随机推荐
wps excel 插入公式 整列
微服务负载均衡器Ribbon
LeetCode
with语句和上下文管理器
相亲模型与有限状态机
JSD-2204-Knife4j框架-处理响应结果-Day07
如何让定时器在页面最小化的时候不执行?
C陷阱与缺陷 第7章 可移植性缺陷 7.10 首先释放,然后重新分配
LeetCode每日一题(1807. Evaluate the Bracket Pairs of a String)
图的邻接矩阵存储
宝塔搭建PESCMS-Ticket开源客服工单系统源码实测
如何用Chrome编辑以及调试代码
Graph adjacency matrix storage
C语言之字符串函数二
(七)《数电》——CMOS与TTL门电路
Pytorch框架学校记录11——搭建小实战完整细节
Goroutine Leaks - The Forgotten Sender
织梦模板加入php代码
扣减库存方案
Telnet弱口令渗透测试









