JavaContentNegotiation
Content negotiation is a mechanism that makes it possible to serve different representation of a same resource (URI). It is useful e.g. for writing Web Services supporting several output formats (XML, JSON, etc.). Server-driven negotiation is essentially performed using the Accept*
requests headers. You can find more information on content negotiation in the HTTP specification.
You can get the list of acceptable languages for a request using the play.mvc.Http.RequestHeader#acceptLanguages
method that retrieves them from the Accept-Language
header and sorts them according to their quality value. Play uses it to set the lang
value of request’s HTTP context, so they automatically use the best possible language (if supported by your application, otherwise your application’s default language is used).
Similarly, the play.mvc.Http.RequestHeader#acceptedTypes
method gives the list of acceptable result’s MIME types for a request. It retrieves them from the Accept
request header and sorts them according to their quality factor.
You can test if a given MIME type is acceptable for the current request using the play.mvc.Http.RequestHeader#accepts
method:
public static Result list() {
List<Item> items = Item.find.all();
if (request().accepts("text/html")) {
return ok(views.html.Application.list.render(items));
} else {
ObjectNode result = Json.newObject();
...
return ok(result);
}
}
- Actions, Controllers and Results
- HTTP routing
- Manipulating the HTTP response
- Session and Flash scopes
- Body parsers
- Actions composition
- Content negotiation
- HTTP programming
- Asynchronous HTTP programming
- The template engine
- HTTP form submission and validation
- Working with JSON
- Working with XML
- Handling file upload
- Accessing an SQL database
- Using the Cache
- Calling WebServices
- Integrating with Akka
- Internationalization
- The application Global object
- Testing your application