[JAVA] Getting Started with Ratpack (4)-Routing & Static Content

Ratpack introductory series

  1. Introduction to Ratpack (1) --What is Ratpack
  2. Introduction to Ratpack (2) --Architecture
  3. Introduction to Ratpack (3) --Hello world detailed explanation
  4. Introduction to Ratpack (4) --Routing & Static Content
  5. Introduction to Ratpack (5) --Json & Registry
  6. Introduction to Ratpack (6) --Promise
  7. Introduction to Ratpack (7) --Guice & Spring
  8. Introduction to Ratpack (8) --Session
  9. Introduction to Ratpack (9) --Thymeleaf

routing

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. ..

Each method for adding a Handler

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) PredicateButtrueWhen
when(boolean/Predicate, Action<Chain>) Boolean orPredicateButtrueWhen,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.

Path literal

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"

Behavior of 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.

Query parameters

This is the part after ? Of the URL. You can get it as a map from getRequest (). GetQueryParams ().

Path parameter

As mentioned above, use getPathToken ().

FORM parameter

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.

Request body

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.

header

Get it via the Headers class, which you can get fromheader (CharSequence)orgetRequest (). GetHeaders ().

cookie

You can get it with Request.getCookies ().

Returns a response

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 ().

Status code

It can be specified by the status (int) method.

cookie

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.

header

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

Getting Started with Ratpack (4)-Routing & Static Content
Getting Started with Ruby
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Transactions
Getting Started with Doma-Annotation Processing
Getting Started with Java Collection
Getting Started with JSP & Servlet
Getting Started with Java Basics
Getting Started with Spring Boot
Getting Started with Ruby Modules
Getting Started with Java_Chapter 5_Practice Exercises 5_4
[Google Cloud] Getting Started with Docker
Getting started with Java lambda expressions
Getting Started with Docker with VS Code
Getting Started with Doma-Criteria API Cheat Sheet
Getting Started with Ruby for Java Engineers
Getting Started with Docker for Mac (Installation)
Getting Started with Parameterization Testing in JUnit
Getting Started with Java Starting from 0 Part 1
Getting started with the JVM's GC mechanism
Getting Started with Language Server Protocol with LSP4J
Getting Started with Creating Resource Bundles with ListResoueceBundle
Getting Started with Java_Chapter 8_About Instances and Classes
Getting Started with Doma-Using Projection with the Criteira API
Getting Started with Doma-Using Subqueries with the Criteria API
Getting Started with Java 1 Putting together similar things
Getting started with Kotlin to send to Java developers
Getting Started with Doma-Using Joins with the Criteira API
Getting Started with Doma-Introduction to the Criteria API
I tried Getting Started with Gradle on Heroku
Getting started with Java programs using Visual Studio Code
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Get started with Gradle
Getting Started with Reactive Streams and the JDK 9 Flow API
Getting Started with GitHub Container Registry instead of Docker Hub