DEV Community

Composite
Composite

Posted on • Edited on

2 3

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay