mn create-app example.micronaut.micronautguide \
--features=views-thymeleaf \
--build=gradle \
--lang=groovy \
--test=spock
Content negotiation in a Micronaut application
Learn how to respond with HTML or JSON depending on the request Accept HTTP header.
Authors: Sergio del Amo
Micronaut Version: 5.0.0
1. Getting Started
In this guide, we will create a Micronaut application written in Groovy.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
3. Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
If you use Micronaut Launch, select Micronaut Application as application type and add views-thymeleaf features.
| If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
5. Views
To use the Thymeleaf Java template engine to render views in a Micronaut application, add the following dependency on your classpath.
implementation("io.micronaut.views:micronaut-views-thymeleaf")
6. Controller
Create a controller that responds with HTML or JSON depending on the request Accept HTTP header.
package example.micronaut
import groovy.transform.CompileStatic
import io.micronaut.http.HttpRequest
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
import io.micronaut.views.ModelAndView
@CompileStatic
@Controller (1)
class MessageController {
@Produces(value = [MediaType.TEXT_HTML, MediaType.APPLICATION_JSON]) (2)
@Get (3)
HttpResponse<?> index(HttpRequest<?> request) { (4)
Map<String, Object> model = [message: 'Hello World']
Object body = accepts(request, MediaType.TEXT_HTML_TYPE)
? new ModelAndView<>('message.html', model)
: model
HttpResponse.ok(body)
}
private static boolean accepts(HttpRequest<?> request, MediaType mediaType) {
request.headers
.accept()
.any { it.name.contains(mediaType.name) }
}
}
| 1 | The class is defined as a controller with the @Controller annotation mapped to the path /. |
| 2 | Use the @Produces annotation to indicate the possible response content types. It matches the Accept header of the request, as you will see in the test. |
| 3 | The @Get annotation maps the method to an HTTP GET request. |
| 4 | You can bind the HTTP Request as a method parameter in a controller’s method. |
For HTML, the previous controller uses a Thymeleaf view:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
7. Test
Write a test that verifies the response content type depending on the request Accept HTTP header.
package example.micronaut
import io.micronaut.http.HttpRequest
import io.micronaut.http.MediaType
import io.micronaut.http.client.BlockingHttpClient
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification
@MicronautTest (1)
class MessageControllerSpec extends Specification {
@Inject
@Client('/') (2)
HttpClient httpClient
void contentNegotiation() {
given:
BlockingHttpClient client = httpClient.toBlocking()
expect:
'{"message":"Hello World"}' == client.retrieve(HttpRequest.GET('/')
.accept(MediaType.APPLICATION_JSON)) (3)
and:
'''\
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Hello World</h1>
</body>
</html>
''' == client.retrieve(HttpRequest.GET('/')
.accept(MediaType.TEXT_HTML))
}
}
| 1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
| 2 | Inject the HttpClient bean and point it to the embedded server. |
| 3 | Creating HTTP Requests is easy thanks to the Micronaut framework fluid API. |
8. Testing the Application
To run the tests:
./gradlew test
Then open build/reports/tests/test/index.html in a browser to see the results.
9. Next Steps
Explore more features with Micronaut Guides.
Read more about Micronaut Views.
10. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
11. License
| All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |