As mentioned above, routing is done by writing a handler that maps to each path in the Chain
class.
The official documentation is in Chain's Javadoc, so please refer to that if you can't explain it here. ..
The most basic method in Chain
is ʻall (Handler), which indicates that all requests will be processed by this handler. Each of the other methods is actually just a convenience method with a "request acceptance condition" added to this method. Internally, each static utility method of
Handlers processes by wrapping the passed
Handler`.
Those that take Class <Handler>
as arguments instead of the instance of Handler
itself will use that class from the context's Registry
.
It doesn't seem to make much sense, but it works great when combined with a DI container such as Guice.
Below, I will explain the main methods (all are impossible due to the large amount).
Method | The condition under which the handler is called |
---|---|
all(Handler) |
you have to |
files() |
See below |
onlyIf(Predicate<Context>, Handler) |
Predicate Buttrue When |
when(boolean/Predicate, Action<Chain>) |
Boolean orPredicate Buttrue When,Action<Chain> Delegated to |
prefix(String, Action<Chain>) |
When the path starts with the specified stringResolved by relative pathAction<Chain> Delegated to |
path(Handler) |
When the request matches the specified path |
get(String, Handler) |
When the specified path is matched and the GET method is called |
post(String, Handler) |
When the specified path is matched and the POST method is called |
patch(String, Handler) |
When the specified path is matched and the PATCH method is called |
put(String, Handler) |
When the specified path is matched and the PUT method is called |
delete(String, Handler) |
When the specified path is matched and the DELETE method is called |
chain.prefix( "hoge", innerChain -> {
innerChain.get( "piyo", handler ); // /hoge/piyo
} );
In addition, Context
provides convenience methods calledbyMethod ()
and byContent
, which allow you to describe branches ideologically.
//path"hoge"Branch with GET and POST when is requested
chain.path( "hoge", ctx -> {
ctx.byMethod( m -> {
m.get( iCtx -> iCtx.render( "get" ) );
m.post( iCtx -> iCtx.render( "post" ) );
} );
} );
// "hoge"Of the request`Accept`Branch by the value of the header
chain.path( "hoge", ctx -> ctx.byContent( accept -> {
accept.json( iCtx -> iCtx.render("json") );
accept.xml( iCtx -> iCtx.render( "xml" ) );
accept.noMatch( iCtx -> iCtx.render( "no match" ) );
} ) );
By the way, the variable name is written in solid here, but it can also be described in the method chain.
Literals such as regular expressions can be used for the character string specified in the path, and path parameters can also be set.
type | Syntax | Example |
---|---|---|
literal | foo |
"foo" |
Regular expression literal | ::<<regex>> |
"foo/::\d+" |
Optional path token | :<<token-name>>? |
"foo/:val?" |
Required path token | :<<token-name>> |
"foo/:val" |
Optional regular expression path token | :<<token-name>>?:<<regex>> |
"foo/:val?:\d+" |
Required regular expression path token | :<<token-name>>:<<regex>> |
"foo/:val:\d+" |
(Translated from Javadoc)
Path parameters can be obtained via the PathTokens
class, which can be obtained withContext.getPathToken ()
.
chain.get( "hoge/:name", ctx -> ctx.render( "name: " + ctx.getPathTokens().get( "name" ) ) );
chain.get( "piyo/:id:\\d+", ctx -> ctx.render( "id: " + ctx.getPathTokens().asLong( "id" ) ) );
path | result |
---|---|
/hoge | 404 |
/hoge/John | "name: John" |
/piyo/hoge | 404 |
/piyo/123 | "id: 123" |
Context
The Context
class is a class that holds information on how a single request is called.
As we saw in Hello world, Handler
is a lambda expression that receives Context
. Therefore, the flow of processing is
Receive Context-> Perform various processing-> Call Context.render () to create a response
It will be in the form of.
This is the part after ?
Of the URL.
You can get it as a map from getRequest (). GetQueryParams ()
.
As mentioned above, use getPathToken ()
.
Form parameters sent from HTTP <form>
tags etc. are obtained via the Form
class using theparse ()
method.
chain.path( "hoge", ctx -> ctx.parse( Form.class ).then( form -> {
ctx.render( "Received: " + form.entrySet() );
} ) );
parse ()
will be described later.
You can get it from getRequest (). getBody ()
.
It's important to note that the getBody ()
method returns the body's Promise
, not the body's contents.
How to use Promise
will be explained in a future post.
Get it via the Headers
class, which you can get fromheader (CharSequence)
orgetRequest (). GetHeaders ()
.
You can get it with Request.getCookies ()
.
To set the response, get the Response
class fromgetResponse ()
and set it in that instance. The actual transmission is done with Context.render (Object)
or Response.send ()
.
It can be specified by the status (int)
method.
The Cookie
class is created by calling thecookie ()
method. There is no need to add the returned Cookie
object to the set returned by thegetCookies ()
method.
You can get a variable set of headers with Response.getHeaders ()
. Convenience methods such as contentType ()
are also available.
Context.redirect(String)
302 Generates a redirect and transitions to the specified path.
Context.clientError(int)
It is used when you want to generate an error in the status code 400 series.
For 404s, the convenience method notFound ()
is provided.
Context.render(Object)
This is the most basic method that returns a response.
BaseDir
To serve static files, Ratpack provides a mechanism called BaseDir
.
First, you need to set the BaseDir Path
to ServerConfig
. You can create the JDK Path
normally, but there is aBaseDir.find ()
method for loading resources from the class loader. There is also a convenience method called ServerConfigBuilder.findBaseDir ()
. find ()
looks for an empty file called .ratpack
in the specified path. If found, it will serve static content using that path as an internal reference path.
Next, we need to create a handler that serves the file from BaseDir. The Chain.files ()
method sends the contents of the file as a response when there is a request from the BaseDir set above to the URL resolved as a relative path.
This is a concrete example. Here, create a folder called public
in the resource and set it to BaseDir.
Create the following as a resource.
resources/public/.ratpack
resources/public/index.html
Path baseDir = BaseDir.find( "public/.ratpack" );
ServerConfig config = ServerConfig.builder()
.baseDir( baseDir )
.development( true ).build();
Action<Chain> handlers = chain -> {
chain.files();
};
RatpackServer.start( server -> server
.serverConfig( config )
.handlers( handlers ) );
Go to http: //localhost:5050/index.html
and you should see the contents of the HTML file you created.
If you want to bind the file to your own path, pass Path
to theContext.render ()
method. You can use the Context.file ()
method to get the file from BaseDir.
Try changing the handler in the above example as follows:
Action<Chain> handlers = chain -> {
chain.files();
chain.get( "hoge", ctx -> ctx.render( ctx.file( "index.html" ) ) );
};
If you visit http: // localhost: 5050 / hoge
, you will see the contents of ʻindex.html`.
Recommended Posts