[英]Using Swagger Documentation for HttpServletRequest
我是 swagger 的新手并使用它的文档。 我目前正在尝试使用 swagger 来显示 PATCH 请求的请求正文。 以前,PATCH方法的参数是正在更新的object的DTO,这样可以很容易地显示object的属性(因为我使用的是SpringBoot,并且使用@Schema
效果很好)。 但是,现在 PATCH 方法的参数是一个 HttpServletRequest。 我不想在 swagger 文档中显示 HttpServletRequest(这似乎是自动发生的),而是想显示 DTO 属性(就像之前所做的那样)。 我想知道是否有办法做到这一点?
非常感谢任何建议!
我假设您正在使用 springdoc-openapi 来生成 SwaggerUI。
要使用它,您可以使用以下 Maven 依赖项,
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webmvc-core</artifactId>
<version>1.4.2</version>
</dependency>
从 springdoc-openapi v1.1.25 开始,HttpServletRequest 和 HttpServletResponse 将被添加到忽略类型列表中。
见下文,
https://github.com/springdoc/springdoc-openapi/issues/57
因此即使我们在 controller 方法中添加 HttpServletRequest 作为参数,它也会被忽略,不会显示在 swagger 中。
所以回到你的问题,要显示 class 的 model,你可以描述另一个参数以及 HttpServletRequest 如下,
@Operation(summary = "Returns a token", description = "Returns A token API", tags = "tokenGeneration", responses = {
@ApiResponse(description = "Successful Operation", responseCode = "200", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Timeresponse.class))),
@ApiResponse(description = "not found Operation", responseCode = "404") })
@PatchMapping("/getTokenPatchRequest")
public ResponseEntity getTokenpatch(HttpServletRequest request, @RequestBody AuthReq2 req) {
log.info("The HttpServlet request header contains the information : " + request.getHeader("Authorization"));
Auth2 的 model class 如下,可以描述您的用户名和密码等示例值。
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
public class AuthReq2 {
@Schema(example = "diannamcallister")
private String userName;
@Schema(example = "test")
private String password;
}
最后 swagger 页面看起来像这样,
当您在授权 header 中输入内容时,如下所示,
这可以通过以下代码通过 HTTP servlet 请求访问,
log.info("The HttpServlet request header contains the information : " + request.getHeader("Authorization"));
springboot 应用程序中的日志条目如下所示,
10:40:01.876 INFO OpenApiController.getTokenpatch:163 - The HttpServlet request header contains the information : stackoverflow
上面的答案不起作用,因为向方法添加另一个参数会破坏方法本身的功能。
有效的解决方案是在 controller 中将 content 参数添加到@RequestBody
注释中:
@RequestBody(description = "Description.",
content = @Content(schema = @Schema(implementation = ObjectDTO.class)));
如何在 swagger 文档中显示 HttpServletRequest?
可以在swagger2的配置中设置, SwaggerConfig.java
new Docket(DocumentationType.SWAGGER_2)
...
.ignoredParameterTypes(HttpSession.class, HttpServletRequest.class, HttpServletResponse.class)
.build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.