当前位置:网站首页>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
- 在配置类中的
basePackage
Must 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-web
Contains the rely on- This method return value type inSpring MVC中没有默认的Converter(转换器),会自动调用
jackson-databind
中的Converter,而jackson-databind
The 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
}
});
边栏推荐
猜你喜欢
STAHL触摸屏维修一体机显示屏ET-316-TX-TFT常见故障
响应式织梦模板清洁服务类网站
Godaddy domain name resolution is slow and how to use DNSPod resolution to solve it
Questions I don't know in database kernel interview(1)
漏洞分析丨HEVD-0x6.UninitializedStackVariable[win7x86]
使用员工管理软件,解锁人力生产力新水平,提高人力资源团队灵活性
Qt设置应用程序开机自启 解决设置失败原因
Pytorch学习记录(八):生成对抗网络GAN
在Cesium中实现与CAD的DWG图叠加显示分析
【中文树库标记---CTB】
随机推荐
2022年秋招,软件测试开发最全面试攻略,吃透16个技术栈
StringTable详解 串池 性能调优 字符串拼接
string
附录A printf、varargs与stdarg A.2 使用varargs.h来实现可变参数列表
徒步,治好了我的精神内耗
位运算简介
StringTable Detailed String Pool Performance Tuning String Concatenation
C专家编程 第1章 C:穿越时空的迷雾 1.5 今日之ANSI C
Godaddy域名解析速度慢问题以及如何使用DNSPod解析解决
STAHL touch screen repair all-in-one display screen ET-316-TX-TFT common faults
【微信小程序】【AR】threejs-miniprogram 安装(76/100)
STAHL触摸屏维修一体机显示屏ET-316-TX-TFT常见故障
那些关于DOM的常见Hook封装(二)
淘宝获取收货地址列表的 API
idea实用快捷键合集——持续更新
关键字搜索:“淘宝商品 API ”
Protocol Buffer 使用
Questions I don't know in database kernel interview(1)
记录第一次给开源项目提 PR
任务调度线程池-应用定时任务