使用上下文路径的POST调用在Spring Boot 2.x中不起作用

问题描述

我正在将Spring Boot应用程序从1.5.x迁移到2.x 我在未尾随/

的情况下对上下文路径进行POST调用时收到405错误
{
    "timestamp": "2020-11-04T12:07:19.065+0000","status": 405,"error": "Method Not Allowed","message": "Request method 'GET' not supported","path": "/hello/"
}

下面是我的代码

application.properties:

spring:
  application:
    name: hello-world-service
server:
  servlet:
    context-path: /hello
  port: 8082

HelloWorldController.java

@RestController
@RequestMapping(value = "/")
public class HelloWorldController {
    
    @PostMapping
    public ResponseEntity<String> helloWorld(@RequestBody HelloDto helloDto){
        return ResponseEntity.ok(helloDto.getName());
    }
}

HelloDto.java

@Data
public class HelloDto {
    private String name;
}

春季启动版本:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.11.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

当我在http:// localhost:8082 / test上进行POST呼叫时,下面的屏幕截图是405状态

enter image description here

但是当我在http:// localhost:8082 / test /上进行POST调用时,它工作正常。下面是快照

enter image description here

有什么方法可以处理我们调用localhost:8082/test会得到与调用localhost:8082/test/相同的结果

解决方法

您没有终结点/hello,而是/hello//hello是主要/根路径,因此,您为/hello/指定了端点:

@RequestMapping(value = "/")
,

在我在application.yml中添加以下属性后,它为我工作了

server:
  tomcat:
    redirect-context-root: false