Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PutMapping and @PostMapping annotations on same method

I want to apply both Put and Post mapping request to a method as show below. It does work for PUT, but not for POST requests. What am I dong wrong?

@RestController
@RequestMapping("/PQR")
public class XController {

    @PutMapping("xyz")
    @PostMapping("xyz")
    public MyDomainObject createOrUpdateDAO(
            HttpServletRequest request, 
            @RequestBody String body) throws IOException {
        //...
    }
}

When I make a POST request, I get a 405 HTTP status code:

[nio-8080-exec-3] o.s.web.servlet.PageNotFound: Request method 'POST' not supported

If I look at this example, same method has same method is mapped for GET and POST requests.

@RequestMapping(value="/method3", method = { RequestMethod.POST,RequestMethod.GET })
@ResponseBody
public String method3() {
    return "method3";
}
like image 529
Raj Avatar asked Dec 25 '17 01:12

Raj


People also ask

Can we use PutMapping instead of PostMapping?

Whether I use PostMapping or PutMapping on my controller method, the effect is the same on the entity, only the field I want to update gets updated and everything is fine.

How can @GetMapping annotation be written by using @RequestMapping method?

From the naming convention we can see that each annotation is meant to handle respective incoming request method type, i.e. @GetMapping is used to handle GET type of request method, @PostMapping is used to handle POST type of request method, etc.

What is the difference between @RequestMapping and GetMapping?

@RequestMapping is used at the class level while @GetMapping is used to connect the methods. This is also an important Spring MVC interview question to knowing how and when to use both RequestMapping and GetMapping is crucial for Java developers.

What is @GetMapping annotation in spring?

Annotation for mapping HTTP GET requests onto specific handler methods. Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod. GET) . Since: 4.3 Author: Sam Brannen See Also: PostMapping , PutMapping , DeleteMapping , PatchMapping , RequestMapping.


1 Answers

Remove @PostMapping and @PutMapping annotations and add method to your @RequestMapping, i.e:

@RequestMapping(value={"/PQR", "xyz"},
    method={RequestMethod.POST,RequestMethod.PUT})
like image 117
ThomasEdwin Avatar answered Oct 02 '22 14:10

ThomasEdwin