0

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/

fr3ddie
  • 406
  • 6
  • 17
Aviral
  • 51
  • 9

2 Answers2

0

You haven't endpoint /hello but /hello/. /hello is main/root path and your endpoint is specified for /hello/ because of this:

@RequestMapping(value = "/")
fr3ddie
  • 406
  • 6
  • 17
  • if I remove `@RequestMapping(value = "/")` then also same behavior , and yes url is /hello I written /test by mistake – Aviral Nov 04 '20 at 18:42
  • It's such how urls works in Spring Boot. `/hello` is default path and `/hello/` is your endpoint. If you want to specify an endpoint for `/hello` you need to delete `context-path: /hello` or change value to `/` and set `/hello` as value in `@RequestMapping`. – fr3ddie Nov 04 '20 at 18:49
0

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

server:
  tomcat:
    redirect-context-root: false
Aviral
  • 51
  • 9