招摇-UI.html 400个错误请求



我已经在我的春季启动项目中集成了swagger。所有 swagger 端点都工作正常,但/product/swagger-ui.html给出 400 错误。

经过一些调试,我发现两个端点之间存在冲突。

在我的应用程序属性文件中,我正在使用server.contextPath=/product.

在我的控制器中,我有以下我认为导致错误的映射。

产品休息控制器.java

@RestController
public class ProductRestController {
// some autowired services
@GetMapping("/{id}")
public ResponseEntity<ProductDTO> getProductById(
@Min(value = 1, message = "id {javax.validation.constraints.Min.message}") @PathVariable Long id,
@RequestAttribute Long tenantId) {
return ResponseEntity.ok(productService.getProductById(id, tenantId));
}
@PutMapping("/{id}")
public ResponseEntity<ProductDTO> updateProduct(
@Min(value = 1, message = "id {javax.validation.constraints.Min.message}") @PathVariable Long id,
@RequestBody HashMap<String, Object> requestBody, @RequestAttribute Long tenantId,
@RequestAttribute Long userId) {
ProductDTO productDTO;
try {
productDTO = objectMapper.convertValue(requestBody, ProductDTO.class);
} catch (IllegalArgumentException e) {
throw new HttpMessageNotReadableException(e.getMessage(), e);
}
Set<ConstraintViolation<ProductDTO>> errors = validator.validate(productDTO, ProductDTO.UpdateProduct.class);
if (!errors.isEmpty()) {
throw new ConstraintViolationException(errors);
}
return ResponseEntity.ok(productService.updateProduct(productDTO, requestBody, id, tenantId, userId));
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteProduct(
@Min(value = 1, message = "id {javax.validation.constraints.Min.message}") @PathVariable Long id,
@RequestAttribute Long tenantId,
@RequestParam(required = false, name = "delete_members") boolean deleteMembers) {
productService.deleteProduct(id, tenantId, deleteMembers);
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null);
}
//other mappings
}

我调试并发现 HandlerExecutionChain 已将此请求转发到getProductById方法,然后它抛出异常无法从字符串转换为 Long。

所以我删除了该映射并再次检查它是否有效,但这次我遇到了 HTTP 405 错误。再次通过调试,我发现堆栈跟踪显示允许的方法为 PUT 和 DELETE。

然后我删除了这两个映射并检查了,它工作正常。

我从中了解到的是,春天以某种方式为/product/swagger-ui.html端点选择/product/{id}映射,然后由于类型不匹配而抛出错误。

问题是为什么会发生这种情况以及如何解决此问题?

编辑:在DispatcherServlet.doDispatch方法中捕获的异常:org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "swagger-ui"

删除 GET 映射后以相同方法捕获的异常:org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

@GetMapping("/{id}")String中给出id值,并且您直接尝试将字符串映射到Long。尝试使用:@PathVariable String id,然后将字符串转换为 Long,如下所示:

Long longId = Long.parseLong(id);

你是对的:通过做/{id} spring,假设 swagger-ui.html 是一个 id。这是网址,如果你的baseUrl=/: http://localhost:8080/swagger-ui.html

虽然它是一个旧线程,但提供我的观点以防万一它对某人有所帮助。

招摇的URL指向ProductRestController,因为它没有任何自己的上下文路径。因此,要解决此问题,请尝试向 ProductRestController 添加上下文路径,类似于 @RequestMapping("v1")。

然后,您的 http://localhost:8080/swagger-ui.html 的 swagger URL 应该可以工作,因为它不会指向任何控制器。

最新更新