public interface ByContentHandler extends Handler
A by-accepts-responder is created by Context.getByContent()
.
It is used to respond differently based on what content the client is willing to accept.
This is useful when a given handler can provide content of more than one type (i.e. content negotiation).
The response to use will be selected based on parsing the "Accepts" header, respecting quality weighting and wildcard matching. The order that types are added to the responder is significant for wildcard matching. The earliest registered type that matches the wildcard will be used.
import ratpack.handling.*; class MyHandler implements Handler { public void handle(final Context context) { // Do processing common to all methods … context.respond(context.getByContent(). json(new Runnable() { public void run() { // JSON responding logic } }). html(new Runnable() { public void run() { // HTML handling logic } }) ); } }
If you are using Groovy, you can use closures as the definitions…
import ratpack.groovy.handling.* class MyHandler extends GroovyHandler { void handle(GroovyContext context) { context.byContent { json { // JSON handling logic } html { // HTML handling logic } } } }If there is no type registered before
Handler.handle(Context)
is called, or the client does not accept any
of the given types, a 406
will be issued to the Context.clientError(int)
that the responder is associated with.
Only the last added runnable for a type will be used. Adding a subsequent runnable for the same type will replace the previous.
Modifier and Type | Method and Description |
---|---|
ByContentHandler |
html(Runnable runnable)
Convenience method to respond with "text/html" mime type.
|
ByContentHandler |
json(Runnable runnable)
Convenience method to respond with "application/json" mime type.
|
ByContentHandler |
plainText(Runnable runnable)
Convenience method to respond with "text/plain" mime type.
|
ByContentHandler |
type(String mimeType,
Runnable runnable)
Register how to respond with the given mime type.
|
ByContentHandler |
xml(Runnable runnable)
Convenience method to respond with "application/xml" mime type.
|
ByContentHandler type(String mimeType, Runnable runnable)
mimeType
- The mime type to register forrunnable
- The action to take if the client wants the given typeByContentHandler plainText(Runnable runnable)
runnable
- the action to take if the client wants plain textByContentHandler html(Runnable runnable)
runnable
- the action to take if the client wants htmlByContentHandler json(Runnable runnable)
runnable
- the action to take if the client wants jsonByContentHandler xml(Runnable runnable)
runnable
- the action to take if the client wants xml