Knife4j实现Script的配置
时间: 2024-03-11 22:51:30 浏览: 199
要在Knife4j中配置Script,需要完成以下步骤:
1. 在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-ui</artifactId>
<version>3.0.2</version>
</dependency>
```
2. 在Swagger配置类中添加以下代码:
```java
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET, responseMessages())
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.enableUrlTemplating(true)
.tags(new Tag("User API", "API for managing users"))
.enable(true)
.globalOperationParameters(
Collections.singletonList(
new ParameterBuilder()
.name("Authorization")
.description("Bearer token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build()
)
)
.additionalModels(new TypeResolver().resolve(User.class))
.groupName("example-api")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(
newRule(
typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class))
)
.ignoredParameterTypes(Pageable.class, Sort.class)
.globalResponseMessage(RequestMethod.GET, responseMessages())
.enableUrlTemplating(true)
.extensions(Lists.newArrayList(new SwaggerExtension() {
@Override
public void apply(OperationContext context) {
// 通过context可获取到当前接口的请求方法、url、参数等信息
context.operationBuilder().operationId(context.requestMappingPattern());
// 获取当前接口的方法名
String methodName = context.methodName();
// 获取当前接口的Class
Class<?> controllerClass = context.getControllerClass();
// 获取当前接口的请求方法(GET/POST/PUT/DELETE等)
RequestMethod requestMethod = context.requestMethod();
// 获取当前接口的请求URL(不含ContextPath)
String requestUrl = context.requestMappingPattern();
// 获取当前接口的请求参数列表
List<ResolvedParameter> parameters = context.getParameters();
// 获取当前接口的响应类型
ResolvedType resolvedType = context.getReturnType();
// 获取当前接口的响应描述
String responseDescription = context.getDocumentationContext().getDocumentationType().getResponseMessage(200).getMessage();
// 获取当前接口的媒体类型列表
List<MediaType> produces = context.getProduces();
// 获取当前接口的消费媒体类型列表
List<MediaType> consumes = context.getConsumes();
// 获取当前接口的HttpHeaders
HttpHeaders headers = context.getHttpHeaders();
// 获取当前接口的响应状态码列表
List<Response> responses = context.getDocumentationContext().getAdditionalResponseMessages();
// 获取当前接口的请求参数列表
List<Parameter> operationParameters = context.getOperationParameters();
// 获取当前接口的请求体参数
ResolvedType requestBodyType = context.getRequestBodyType();
// 获取当前接口的请求体描述
String requestBodyDescription = context.getDocumentationContext().getDocumentationType().getRequestMessage().getMessage();
// 获取当前接口的请求体媒体类型列表
List<MediaType> requestBodyConsumes = context.getConsumes();
// 获取当前接口的请求体参数列表
List<ResolvedParameter> resolvedParameters = context.getParameters();
// 获取当前接口的响应体参数类型
ResolvedType responseBodyType = context.getResponseBodyType();
// 获取当前接口的响应体描述
String responseBodyDescription = context.getDocumentationContext().getDocumentationType().getResponseMessage(200).getMessage();
// 获取当前接口的响应体媒体类型列表
List<MediaType> responseBodyProduces = context.getProduces();
}
}));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Example API Documentation")
.description("Documentation for the Example API")
.version("1.0.0")
.build();
}
private List<SecurityScheme> securitySchemes() {
return newArrayList(
new ApiKey("ApiKey", "ApiKey", "header")
);
}
private List<SecurityContext> securityContexts() {
return newArrayList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/.*"))
.build()
);
}
private List<SecurityReference> defaultAuth() {
return newArrayList(
SecurityReference.builder()
.reference("ApiKey")
.scopes(new AuthorizationScope[0])
.build()
);
}
private List<ResponseMessage> responseMessages() {
return newArrayList(
new ResponseMessageBuilder()
.code(500)
.message("Internal Server Error")
.responseModel(new ModelRef("Error"))
.build(),
new ResponseMessageBuilder()
.code(403)
.message("Forbidden")
.build()
);
}
}
```
其中,extensions()方法中实现了SwaggerExtension接口,可以通过该接口的apply()方法来扩展Swagger的功能。
3. 在需要添加Script的接口上添加@ApiOperation注解,并设置notes属性为需要执行的脚本,例如:
```java
@RestController
@RequestMapping("/api")
@Api(value = "User API", tags = {"User API"})
public class UserController {
@GetMapping("/users")
@ApiOperation(value = "Get all users", notes = "Script:\n" +
"```js\n" +
"if (params.page === 1) {\n" +
" return 'success';\n" +
"} else {\n" +
" return 'fail';\n" +
"}\n" +
"```")
public List<User> getUsers() {
// ...
}
}
```
在上述代码中,@ApiOperation注解的notes属性中包含了一个JavaScript脚本,用于根据参数page返回不同的结果。
4. 启动应用程序,访问Swagger UI页面,即可看到添加了Script的接口,并可以在页面上执行对应的脚本。
阅读全文