Chuyển đến nội dung

Bài 4 · Getting Started

Your First Controller

Write your first Micronaut endpoint with @Controller and @Get, run it with Gradle or Maven, call it with curl, and see how requests are routed to methods.

Time to answer a request. In Micronaut an HTTP endpoint is a class annotated with @Controller whose methods carry verb annotations such as @Get and @Post. You do not extend a base class, implement an interface or register anything by hand. Annotate, build, run, and the route exists.

This lesson creates a controller, runs the app, calls it, and then explains how the framework turns a request path into a method call. The real Micronaut code is read-only here. The runnable examples are Java stand-ins: a reflection-based router that behaves like Micronaut's annotation routing, and a real loopback HTTP server built with the JDK that you can call from the same program.

A controller in five lines

Java
package com.example;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;

@Controller("/hello")
public class HelloController {

    @Get
    @Produces(MediaType.TEXT_PLAIN)
    public String index() {
        return "Hello from Micronaut";
    }
}

@Controller("/hello") sets the base path for every method in the class. @Get with no argument maps GET /hello. @Produces sets the Content-Type header; without it, Micronaut would default to JSON for most return types, which is the usual choice for APIs. A String return value becomes the response body with status 200 OK.

A second method shows a path variable:

Java
@Get("/{name}")
@Produces(MediaType.TEXT_PLAIN)
public String greet(String name) {
    return "Hello, " + name;
}

in the path binds to the method parameter with the same name. If the name did not match, you would write @PathVariable("who") String name. Beyond that, controllers and routing goes into detail on variables, query parameters and bodies.

Running the application

From the project directory:

Terminal
./gradlew run          # Gradle
./mvnw mn:run          # Maven

The first run compiles your code, so the annotation processor writes the definitions, then starts Netty. The log ends with a line like Startup completed in 450ms. Server Running: http://localhost:8080. Call it:

Terminal
curl http://localhost:8080/hello
curl http://localhost:8080/hello/Ada

The expected responses are Hello from Micronaut and Hello, Ada. To change the port, set micronaut.server.port in application.yml, or use micronaut.server.port=-1 to pick a random free port, which is useful in tests.

Use ./gradlew run -t (continuous build) or the Maven mn:run goal with watch mode so the server restarts after a source change. Dev-mode restarts are fast because there is little to scan.

What happens to a request

Request lifecycle

Netty receives it Bytes become an HTTP request.
Router matches Method plus path picks a route.
Binding Path, query and body fill parameters.
Response The return value becomes the body.

Filters can run before and after these steps.

1 / 2

At build time, the processor records each route: GET /hello goes to HelloController.index. At runtime the router holds a prebuilt table of these routes, so matching is a lookup, not a scan. Argument binding uses compile-time metadata too, so Micronaut does not need to read parameter names by reflection.

Stand-in 1: annotation routing by reflection

Java annotations are real, so we can build a toy version of the routing idea. The program declares its own @Controller and @Get, collects routes from a class, and matches a request line. Micronaut computes the table during compilation; this stand-in computes it at runtime by reflection, which is the difference between the two, but the matching behavior is the same.

Java A toy annotation router

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in 2: a real HTTP server on loopback

The JDK ships a small HTTP server, com.sun.net.httpserver. This example starts one on a free loopback port, maps /hello the way the controller does, and calls it with HttpClient, so you see a genuine request and response. It is not Netty or Micronaut, only a runnable analogue of "an app answering GET /hello".

Java Serve and call /hello

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the third call: a verb with no matching route yields 405, and an unknown path would yield 404. Micronaut behaves the same way, returning a JSON error body in the vnd.error or problem format.

Common mistakes

  • Forgetting annotation processing. The controller compiles, but the route is missing at runtime. Rebuild after enabling processing in your IDE.
  • Controller in the wrong package. Classes outside the root package of your Application are not found unless you configure scanning.
  • Returning a custom object with no JSON module. Add the Serde or Jackson feature; see JSON and Serialization.
  • Expecting @Controller beans to be per-request. Controllers are singletons by default, so keep per-request state in method variables.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which annotation maps an HTTP GET to a method?

    @Get, @Post, @Put, @Delete and similar annotations bind HTTP verbs to controller methods.
  2. 2. In @Controller("/hello") with @Get("/{name}"), which URL reaches the method?

    The controller path and method path are joined, and {name} binds the last segment.
  3. 3. What does a method that returns a String with no other annotation produce by default?

    The returned value becomes the body and the status defaults to 200 OK.
  4. 4. A GET route exists but you send a POST to the same path. What is the likely status?

    The path matches but not the verb, so the server answers 405.

Summary

  • @Controller("/base") plus @Get, @Post and friends define endpoints.
  • Path variables in bind to parameters of the same name.
  • Run with ./gradlew run or ./mvnw mn:run and call it with curl.
  • Routes are recorded at compile time, so matching at runtime is a table lookup.
  • No match gives 404, a path match with the wrong verb gives 405.

Next: Ahead-of-Time Compilation

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.