Spring Mvc and MediaType for consumes in @RequestM

2019-06-26 07:44发布

I'm implementing a REST application using Spring Boot. I want to specify the consumes parameter for the @RequestMapping annotation. The rest call should be something like:

http: // mysite.com/resource/123

In the controller I handle this as follows:

    @RequestMapping(value = "/resource/{id}", method = RequestMethod.GET, 
consumes = XXX, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Scenario getResource(@PathVariable("id") final long id) {
        //...
    }

The default value, i.e. all, is obvious and not specific. So, which should be the correct MediaType for consumes?

4条回答
来,给爷笑一个
2楼-- · 2019-06-26 08:14

It depends on your requirements. If you only want to allow consumption of JSON, for example, then:

@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, ...)

If you want to consume multiple media types, then you can specify them in an array:

@RequestMapping(consumes = {
        MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE,
}, ...)
查看更多
可以哭但决不认输i
3楼-- · 2019-06-26 08:16

To consume data from url path or url query param, you don't need to explicitly specify any media format. It works with the default format.

@RequestMapping(value={"/resource/{id}"}, method={RequestMethod.GET})
public String getResource1(@PathVariable("id") Long id){
    // other code here
    return "";
}

@RequestMapping(value={"/resource/{id}"}, method={RequestMethod.POST})
public String getResource2(@PathVariable("id") Long id, @ModelAttribute Person person){
    // other code here
    return "";
}
查看更多
倾城 Initia
4楼-- · 2019-06-26 08:31

According to the documentation, consumes has to match the value of Content-Type header so the value you need to send for the mapping depends on what the client sets in the header.

查看更多
Rolldiameter
5楼-- · 2019-06-26 08:40

With just a path variable, you do not need any content type. If you leave it blank, Spring will map all /resource/{id} requests to this handler regardless of the content type header. If you want to specify a content type, choose a default one like text/plain. But be aware that you have to change the request to have the same content-type header.

查看更多
登录 后发表回答