DEV Community

Composite
Composite

Posted on • Edited on

How to make all textual response as UTF-8 on Jooby

Only 3 steps. (on 2.x or later)

  • Use Decorator.
  • Make handler with set current response type and charset UTF-8.
  • return next.apply(ctx); for next response procedure.
import io.jooby.Jooby;
import io.jooby.MediaType;
import java.nio.charset.StandardCharsets;

public class App extends Jooby {

  {
    // use Decorator.
    decorator(next -> ctx -> {
      // get response content-type.
      final MediaType responseType = ctx.getResponseType();
      // if content-type is text-specific
      if(responseType.isTextual())
      // override response type with current media type and always use UTF-8 charset!
        ctx.setResponseType(responseType, StandardCharsets.UTF_8);
      // pipe next response procedure.
      return next.apply(ctx);
    });

    get("/", ctx -> "Abc가나다漢文");
  }

  public static void main(final String[] args) {
    runApp(args, App::new);
  }
}
Enter fullscreen mode Exit fullscreen mode

Then run jooby application, connect localhost:8080 or your another application host on your browser and see your unicode response.

Simple and easy ♡!

UPDATE:
27 Jul, 2021: getRequestType -> getResponseType

Top comments (0)