Swagger GET请求传递id参数,URL后缀变成了{?id}

背景

新建的springboot项目,通过swagger调试接口的时候,发现GET请求,我只传递了id一个参数,然后在swagger中,该接口的url的后缀竟然变成了{?id},在这里插入图片描述

当我请求接口的时候就直接报错了:

java.lang.IllegalArgumentException: Invalid character found in the request target [/official/admin/api/news/getById%7B?id}&id=1 ]. The valid characters are defined in RFC 7230 and RFC 3986
	at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:494) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:269) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.48.jar:9.0.48]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.48.jar:9.0.48]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) [tomcat-embed-core-9.0.48.jar:9.0.48]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.48.jar:9.0.48]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_181]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_181]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.48.jar:9.0.48]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]

说明URL变了,就变成了上边的带?的地址。

解决

原因如下:

@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.project.controllers"))  // 确保指向正确的包路径
                .paths(PathSelectors.any())
                .build()
                .enableUrlTemplating(true);  // 开启URL模板化,应当改成false或者不配置,改为false之后,一切都正常了
    }
}

你可能感兴趣的:(SpringBoot,Swagger)