Spring Boot中Swagger页面输入框缺失及请求方式显示异常问题
Fixing Swagger Issues in Your Spring Boot RestAPI
Hey there! Let's work through these two Swagger problems you're encountering—they're super common, so we can sort them out quickly.
1. Swagger shows all HTTP methods (POST/PUT/etc.) even though you only wrote GET endpoints
This usually happens when you're using @RequestMapping without specifying the HTTP method explicitly. Unlike @GetMapping, @RequestMapping defaults to matching all HTTP request methods, which is why Swagger lists them all.
Fixes:
- Switch to
@GetMapping(the cleanest approach):
Replace your existing@RequestMappingannotation with@GetMapping, which is specifically for GET requests. Example:@GetMapping("/getUser/{id}") public User getUser(@PathVariable Long id) { // Your logic here } - Or specify the method in
@RequestMapping:
If you need to stick with@RequestMapping, add themethodattribute to restrict it to GET only:@RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET) public User getUser(@PathVariable Long id) { // Your logic here }
2. No input box for @PathVariable parameter id in the /getUser Swagger UI
This is almost always because Swagger can't map the parameter to your endpoint's path, or it can't read the parameter name correctly. Here's how to fix it:
Fixes:
- Make sure the path variable is defined in your endpoint URL:
You need to include{id}in your endpoint path so Swagger recognizes it as a path parameter. For example:// Wrong: Path doesn't include {id} @GetMapping("/getUser") public User getUser(@PathVariable Long id) { ... } // Correct: Path includes {id} @GetMapping("/getUser/{id}") public User getUser(@PathVariable Long id) { ... } - Explicitly name the path variable (for older Java versions):
If your Java compiler isn't preserving parameter names (common in Java 8 and below without specific settings), add thenameattribute to@PathVariable:@GetMapping("/getUser/{id}") public User getUser(@PathVariable(name = "id") Long id) { ... } - Enable parameter name retention in your build config:
For Maven, add the<parameters>true</parameters>setting to yourmaven-compiler-plugininpom.xmlto ensure parameter names are kept during compilation:<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <!-- Match your Java version --> <target>1.8</target> <parameters>true</parameters> </configuration> </plugin> </plugins> </build>
After applying these changes, restart your Spring Boot app and refresh the Swagger UI—both issues should be resolved!
内容的提问来源于stack exchange,提问作者Salah
相关产品推荐
相关产品推荐

