This will work:
@RequestMapping(value = "/test", method = RequestMethod.POST,
headers = {"content-type=application/json"}) {
.......
}
If I add another value to it like the following, then it will fail and tell me this:
The specified HTTP method is not allowed for the requested resource (Request method 'POST' not supported)
@RequestMapping(value = "/test", method = RequestMethod.POST,
headers = {"content-type=application/json","content-type=application/xml"}) {
.......
}
I guess this is because Spring thinks the two content type values have "AND" relationship but instead I want them to be "OR".
Any suggestions?
Thanks!
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
The @RequestMapping annotation provides a header element to narrow down the request mapping based on headers present in the request. You can specify the header element as myHeader = myValue. In the above code snippet, the headers attribute of the @RequestMapping annotation narrows down the mapping to the post() method.
value method is an alias for path method. This is an alias for path(). For example @RequestMapping("/foo") is equivalent to @RequestMapping(path="/foo"). So both methods are similar in that sense.
RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam .
If you are using Spring 3.1.x. You can look at using consumes, produces attributes of @RequestMapping annotation. Here is the Spring blog post on the improvements:
http://spring.io/blog/2011/06/13/spring-3-1-m2-spring-mvc-enhancements/
Snippet from the doc above:
@RequestMapping(value="/pets", headers="Content-Type=application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// ...
}
is replaced by:
@RequestMapping(value="/pets", consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// ...
}
In addition, if you need multiple media types. You can do the following:
produces={"application/json", "application/xml"}
consumes={"application/json", "application/xml"}
Have you tried doing content-type=application/json,application/xml
?
Not sure if it would work but putting two content-type
headers in there I think only one will win.
OR
possibily use two RequestMapping
annotations on the same method with different content-type
headers?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With