6.10 Response Content-Type
A Micronaut’s controller action produces application/json
by default. Nonetheless you can change the Content-Type
of the response with the @Produces
annotation or the produces
member of the HTTP method annotations.
import io.micronaut.context.annotation.Requires;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
@Controller("/produces")
public class ProducesController {
@Get (1)
public HttpResponse index() {
return HttpResponse.ok().body("{\"msg\":\"This is JSON\"}");
}
@Produces(MediaType.TEXT_HTML)
@Get("/html") (2)
public String html() {
return "<html><title><h1>HTML</h1></title><body></body></html>";
}
@Get(value = "/xml", produces = MediaType.TEXT_XML) (3)
public String xml() {
return "<html><title><h1>XML</h1></title><body></body></html>";
}
}
import io.micronaut.context.annotation.Requires
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
@Controller("/produces")
class ProducesController {
@Get (1)
HttpResponse index() {
HttpResponse.ok().body("{\"msg\":\"This is JSON\"}")
}
@Produces(MediaType.TEXT_HTML) (2)
@Get("/html")
String html() {
"<html><title><h1>HTML</h1></title><body></body></html>"
}
@Get(value = "/xml", produces = MediaType.TEXT_XML) (3)
String xml() {
return "<html><title><h1>XML</h1></title><body></body></html>"
}
}
import io.micronaut.context.annotation.Requires
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
@Controller("/produces")
class ProducesController {
@Get (1)
fun index(): HttpResponse<*> {
return HttpResponse.ok<Any>().body("{\"msg\":\"This is JSON\"}")
}
@Produces(MediaType.TEXT_HTML)
@Get("/html") (2)
fun html(): String {
return "<html><title><h1>HTML</h1></title><body></body></html>"
}
@Get(value = "/xml", produces = [MediaType.TEXT_XML]) (3)
fun xml(): String {
return "<html><title><h1>XML</h1></title><body></body></html>"
}
}
1 | The default content type is JSON |
2 | Annotate a controller’s action with @Produces to change the response content type. |
3 | Setting the produces member of the method annotation also changes the content type. |