Java Reference
In-Depth Information
Here, we create a
Response
with the
ResponseBuilder
interface, using the desired media
type and language pulled directly from the
HttpHeaders
injected object.
Variant processing
JAX-RS also has an API to dealwith situations in which you have multiple sets of media
types, languages, and encodings you have to match against. You can use the interface
javax.ws.rs.core.Request
and the class
javax.ws.rs.core.Variant
to perform these
complex mappings. Let's look at the
Variant
class first:
package
package
javax
.
ws
.
rs
.
core
.
Variant
public
public class
class
Variant
Variant
{
public
public
Variant
(
MediaType mediaType
,
Locale language
,
String encoding
) {...}
public
public
Locale
getLanguage
() {...}
public
public
MediaType
getMediaType
() {...}
public
public
String
getEncoding
() {...}
}
The
Variant
class is a simple structure that contains one media type, one language, and one
encoding. It represents a single set that your JAX-RS resource method supports. You build a
list of these objects to interact with the
Request
interface:
package
package
javax
.
ws
.
rs
.
core
.
Request
public
public interface
interface
Request
Request
{
Variant
selectVariant
(
List
<
Variant
>
variants
)
throws
throws
IllegalArgumentException
;
...
}
The
selectVariant()
method takes in a list of
Variant
objects that your JAX-RS method
supports. It examines the
Accept
,
Accept-Language
, and
Accept-Encoding
headers of the
incoming HTTP request and compares them to the
Variant
list you provide to it. It picks the
variant that best matches the request. More explicit instances are chosen before less explicit
ones. The method will return null if none of the listed variants matches the incoming accept
headers. Here's an example of using this API:
@Path
(
"/myservice"
)
public
public class
class
MyService
MyService
{