From the course: Java EE: RESTful Service with JAX-RS 2.0
@Consumes and @Produces
From the course: Java EE: RESTful Service with JAX-RS 2.0
@Consumes and @Produces
- [Instructor] All resource methods can consume and produce content of almost any type. If you make a post request to a URI such as API slash books the rest API expects the HTTP body to contain a pay load that represents the resource it should create. This resource can be represented using any media type. Although typically it will be represented in either JSON or XML. Well it could be plain text, binary or a custom format. It doesn't matter, as long as there is a method in the resource class that can consume that media type. So the question is, how does the resource class know the methods media type and how does it select the right method to deal with it? Well, in the header of the HTTP request, there is a content type field that specifies the media type. And on the other end, the server end, the resource class has a method annotated with the matching type. So for example, if a request has a content type set to application JSON, the resource method that consumes this request is the method annotated with the same type. And likewise, if the content type were application XML, the method annotated media type application XML would handle that request. Just as a method can consume a payload of the given type it can produce a response payload of a specific type too. In the case of a post request the created resource can be returned back to the client. Conventionally, it is returned back in the same format as it was received. So returns back as JSON if it was posted in JSON. Nevertheless, this does not have to be the case. There is another HTTP header that specifies the accepted return media type and there is a matching annotation on the resource methods also. Such a method will be annotated with the produces annotation and passes the media type application JSON. So if a full example would be an HTTP post request with a content type of JSON and an accept type of JSON. And the corresponding resource method would be annotated appropriately with both the consumes and the produces annotation with immediate type application JSON. Okay so let's jump to the code and add these media type annotations.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
(Locked)
Define the REST contract3m 42s
-
(Locked)
Inheritance or XML configuration3m 25s
-
(Locked)
Define the API root3m 14s
-
Create the resource entity5m 37s
-
(Locked)
Create the resource methods6m 16s
-
(Locked)
Path parameters2m 35s
-
(Locked)
Add path paramaters3m 21s
-
@Consumes and @Produces2m 7s
-
(Locked)
Add the media types4m 56s
-
(Locked)
Challenge: Add resource methods31s
-
(Locked)
Solution: Add resource methods1m 56s
-
(Locked)
-
-
-
-