[JAVA] Introduction to Ratpack (3) --hello world detailed explanation

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

hello world detailed explanation

Here, we will make the Hello World sample of First article a little more complicated and aim to "get used to water" called Ratpack.

In addition, since the type is specified here, it is intentionally written redundantly. Do not throw stones.

public final class Sample3_HelloWorldRevisited {


    public static void main( String[] args ) throws Exception {

        ServerConfig config = ServerConfig.builder()
                                          .port( 5050 )
                                          .connectTimeoutMillis( 10000 )
                                          .threads( 8 )
                                          .development( true )
                                          .build();

        Registry registry = Registry.empty();

        Action<Chain> handlers = ( Chain chain ) -> {

            Handler handler = ( Context ctx ) -> {
                ctx.render( "hello, world" );
            };

            chain.get( handler );
        };

        RatpackServer.of( spec -> spec.serverConfig( config )
                                      .registry( registry )
                                      .handlers( handlers ) )
                     .start();
    }

}

ServerConfig

This class is for changing the server settings. You can set the port number etc. from here.

I think it's easiest to use ServerConfigBuilder as it is available. There are also methods for reading settings from files, such as json () and yaml (). There are other methods for setting from system properties and arguments, so you can create ServerConfig the way you like.

development(boolean)

A flag that enables the developing mode. If enabled, a handler will be added automatically when an error occurs.

Below is a comparison when a 404 error is actually generated. In addition to the presence of a Ratpack 404 error page, you will be warned to define your own handler in the log.

development(true) 404_1.PNG

19:02:26.231 [ratpack-compute-1-2] ERROR ratpack.error.internal.DefaultDevelopmentErrorHandler - 404 client error for request to /hoge

development(false) 404_2.PNG

19:00:55.861 [ratpack-compute-1-4] WARN ratpack.error.internal.DefaultProductionErrorHandler - Default production error handler used to render client error, please add a ratpack.error.ClientErrorHandler instance to your application (method: GET, uri: /hoge)

development (true) is easy to use, but it seems recommended to create your own ʻErrorHandler` in a production environment.

There are two types of error handlers, ClientErrorHandler and ServerErrorHandler.

ClientErrorHandler is called when there is a problem with a client request, such as a 404. Overrides the ʻerror ()method that takes theContext and ʻint status codes as arguments.

ServerErrorHandler is called when an error occurs in the handler. There is a ʻerror ()method that takes aContext and a Throwablethat represents the exception that occurred. SinceServerErrorHandler` is the last bastion of error handling in Ratpack, it is basically recommended not to throw an exception.

By the way, as this method has Throwable as an argument instead of ʻException, it will be processed even if ʻError occurs. In Java, it is generally recommended not to catch ʻError`, so in that case it is better not to try to recover.

Registry

This class registers parts such as modules in the Ratpack server. We won't use anything this time, so we'll use an empty implementation. The above error handlers etc. can be used by registering in this registry.

handlers

Ratpack routes by multiple Handlers grouped by Chain. The Chain.get (String, Handler) method binds the HTTP GET request to the argument handler. The string of the first argument is the path. If omitted like this time, it will be mapped to the route.

Context.render (Object) is the method that outputs the body of the response. Since String is passed as an argument this time, that character string will be output as it is, but you can also pass an object other than the character string. render () is a mechanism in which Renderer registered in Registry is called according to the type and converted into a response. String has a built-in Renderer (to be exact, CharSequence), so you can call it withContext.render ()without explicitly registering a renderer.

RatpackServer.of( spec -> spec.serverConfig( config )
                              .registry( registry )
                              .handlers( handlers ) )
             .start();

Create a RatpackServer instance by setting ServerConfig, Registry, and Handler in the ʻof ()method. Thestart ()` method starts the server and starts accepting requests.

Each method of RatpackServerSpec (serverConfig () ,registry (),handler ()andhandlers ()) has an instance of the corresponding class as an argument and via ʻAction. There are various things to set. Personally, as I mentioned in the example, I find it easier to use instances for configs and registries, and ʻAction for handlers. This area is subjective, so we recommend that you try various things.

Recommended Posts

Introduction to Ratpack (3) --hello world detailed explanation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
Introduction to Ratpack (2)-Architecture
Introduction to Ratpack (5) --Json & Registry
Introduction to Ratpack (7) --Guice & Spring
Introduction to Ratpack (1) --What is Ratpack?
Introduction to Ratpack (Extra Edition) --Using Sentry
Introduction to Ruby 2
Introduction to Ratpack (Extra Edition) --Ratpack written in Kotlin
Read "Hello world"
Introduction to web3j
Java, Hello, world!
Returning to the beginning, Java-Kisama mocked Hello World-
[Java] Introduction to Java
Introduction to migration
Java Hello World
Introduction to java
Try to display hello world with spring + gradle
Introduction to Doma
First JavaFX ~ Easy introduction Hello world GUI creation ~
Easy to display hello world with Rails + Docker
[Introduction] Display Android Studio Hello World on the emulator
Introduction to JAR files
"Hello World" in Java
Introduction to bit operation
Java Learning (1)-Hello World
Read System.out.println ("hello, world")
Let's write Hello World
Hello world in node.js
Introduction to PlayFramework 2.7 ① Overview
Introduction to design patterns (introduction)
Hello World in Java
Introduction to Practical Programming
Introduction to javadoc command
Studying Java-Part 1-Hello World
Introduction to jar command
Detailed explanation Actor (libGDX)
Introduction to lambda expression
Introduction to java command
Hello World on WebAssembly
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Hello World with Micronaut
Introduction to javac command
[Introduction to Docker] ~ The shortest explanation until starting jupyter lab ~
[Introduction to MVEL] Aiming to be the best MVELer in the world