javaspring-bootspring-mvccontextpathspring-boot-2

POST call using context-path not working in spring boot 2.x


I am migrating my spring boot application from 1.5.x to 2.x I am getting 405 error while making POST call to context path without trailing /

{
    "timestamp": "2020-11-04T12:07:19.065+0000",
    "status": 405,
    "error": "Method Not Allowed",
    "message": "Request method 'GET' not supported",
    "path": "/hello/"
}

below is my code

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;
}

spring boot version:

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

When I make POST call on http://localhost:8082/test , I get 405 status below is the screenshot

enter image description here

But when I make POST call on http://localhost:8082/test/ , It worked fine. below is the snapshot

enter image description here

Is there any way to handle scenario where we make call to localhost:8082/test will give same result as we make a call to localhost:8082/test/


Solution

  • It worked for me after I added below property in application.yml

    server:
      tomcat:
        redirect-context-root: false