You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring WebFlux的Swagger V3中为查询参数配置正则校验

解决方案

要让查询参数id遵循正则表达式[a-zA-Z0-9]{5,15}并在Swagger界面给出输入提示,你可以通过@Parameter注解的schema属性结合@Schema注解实现,具体操作如下:

  1. 在@Parameter中配置schema属性,通过@Schema的pattern字段指定正则规则,同时补充description和example明确规则要求,让用户更清晰理解输入规范。

修改后的路由类代码如下:

@Configuration
public class FacilitiesRouter {
  @RouterOperation(path = "/facilities", produces = {
      MediaType.APPLICATION_JSON_VALUE},
      beanClass = FacilitiesHandler.class, method = RequestMethod.GET, beanMethod = "getFacility",
      operation = @Operation(operationId = "getFacility", summary = "Get facilities1 by key",
          description = "Retrieves one or more facilities1 based on provided keys .",responses = {
          @ApiResponse(responseCode = "200", description = "successful operation",
              content = @Content(schema = @Schema(implementation = FacilitiesResponse.class)))
      },
          parameters = {
              @Parameter(in = ParameterIn.QUERY, name = "id", required = true,
                  schema = @Schema(
                      pattern = "[a-zA-Z0-9]{5,15}",
                      example = "XYZ789",
                      description = "ID必须为5-15位,仅包含字母和数字"
                  )
              )
      }
      ))
  @Bean
  public RouterFunction<ServerResponse> route(FacilitiesHandler handler) {
    return RouterFunctions.route(GET("/facilities"), handler::getFacility);
  }
}
  1. 配置完成后重启应用,访问Swagger UI即可看到效果:
    • 参数输入框旁会显示规则描述
    • 输入不符合正则的内容时,Swagger UI会即时弹出验证错误提示

如果需要后端也对参数做校验,可以在FacilitiesHandler的getFacility方法参数上添加@Pattern(regexp = "[a-zA-Z0-9]{5,15}")注解,并确保项目引入spring-boot-starter-validation依赖,实现前后端双重校验。

内容的提问来源于stack exchange,提问作者Abdullah Imran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:51:36