当前位置:网站首页>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
}
});边栏推荐
猜你喜欢

OSG Notes: Set DO_NOT_COMPUTE_NEAR_FAR to manually calculate far and near planes

扣减库存方案

Nacos 配置中心

函数(二)

with语句和上下文管理器

移植MQTT源码到STM32F407开发板上

An online JVM FullGC made it impossible to sleep all night and completely crashed~

MySQL 中出现的字符编码错误 Incorrect string value: ‘\x\x\x\x‘ for column ‘x‘

STAHL touch screen repair all-in-one display screen ET-316-TX-TFT common faults

ISC2022 HackingClub白帽峰会倒计时1天!最全议程正式公布!元宇宙集结,精彩绝伦!
随机推荐
kubernetes各名词缩写
C陷阱与缺陷 第7章 可移植性缺陷 7.9 大小写转换
响应式织梦模板美容整形类网站
附录A printf、varargs与stdarg A.3 stdarg.h ANSI版的varargs.h
淘宝获取收货地址列表的 API
微服务负载均衡器Ribbon
[译] 容器和 Kubernetes 中的退出码完整指南
LeetCode·32.最长有效括号·栈·动态规划
MySQL语法基础
Hiking, cured my mental internal friction
ahooks 是怎么处理 DOM 的?
任务调度线程池基本介绍
Common pits in the Go language
Simple test of the use of iptables
面试突击70:什么是粘包和半包?怎么解决?
织梦通过数据库查询调用当前文章的留言
system collection
Transplant MQTT source code to STM32F407 development board
Questions I don't know in database kernel interview(1)
Jmeter实战 | 同用户重复并发多次抢红包