Use Thymeleaf with Azure Functions

I think that it is common to return JSON if it is serverless, but html can also be returned. So, without the template engine, creating html would be a pain, so I tried to use Thymeleaf.

Premise

Basically, it is a prerequisite that the environment is constructed according to the following. (It's ok if you're creating a project from a Maven archetype.) https://docs.microsoft.com/ja-jp/azure/azure-functions/functions-create-first-java-maven

First, an example of simply returning html

Function.java


public class Function {
    @FunctionName("html")
    public HttpResponseMessage<String> html(@HttpTrigger(name = "html", methods = {
            "get" }, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<String> req) {
        String html = "<html><head><title>Take it</title></head><body><h1>Bode</h1></body></html>";
        HttpResponseMessage<String> res = req.createResponse(200, html);
        res.addHeader("Content-Type", "text/html");

        return res;
    }
}

Assemble the html by yourself and return it with HttpResponseMessage type. At this time, if you do not set Content-Type to text / html with addHeader, the browser will recognize it as just a character string.

It would be nice if the html is as simple as this, but when it gets complicated or dynamic elements come out, it will be painful, so I would like to use Thymeleaf.

Use Thymeleaf

First, add thymeleaf to the dependency of pom.xml. The version is up to date at this time.

pom.xml


<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.9.RELEASE</version>
</dependency>

Then the sauce.

Fuction.java


public class Function{
    @FunctionName("thymeleaf")
    public HttpResponseMessage<String> thymeleaf(@HttpTrigger(name = "thymeleaf", methods = {
            "get" }, authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<String> req) {
        
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setTemplateMode(TemplateMode.HTML);

        templateResolver.setPrefix("template/");
        templateResolver.setSuffix(".html");
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        Context context = new Context();
        context.setVariable("message", "hogehoge");
        String html = templateEngine.process("test", context);

        HttpResponseMessage<String> res = req.createResponse(200, html);
        res.addHeader("Content-Type", "text/html");

        return res;
    }
}

I usually use it with Spring, so I wasn't really aware of it, but there are several types of Template Resolver. This time, we will use ClassLoaderTemplateResolver.

Also, in order to pass the value to Thymeleaf side, it is necessary to create a Context object. I think it's like a Model in Spring.

test.html


<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Thymeleaf</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p th:text="${message}">Thymeleaf!!</p>
  </body>
</html>

I made html like this. It is located in src / main / resources / template.

After that, you can start it, deploy it, and check the operation.

Impressions

This time, Thymeleaf related instance is generated in the method, but it may be better to execute it in the constructor and make it an instance variable. However, it doesn't make sense if the constructor is executed every time it is accessed. If it is serverless, I do not understand the operation around here, so I think that I have to verify it someday.

Also, I feel that if you do so far, you should make it quickly with Spring Boot. If it's serverless, it has an Auto Scaling function, so it's a merit that you can take advantage of it.

Recommended Posts

Use Thymeleaf with Azure Functions
Use Azure Bing SpellCheck with Java
Use Java 11 with Google Cloud Functions
Use ProGuard with Gradle
Azure functions in java
Use Puphpeteer with Docker
Use XVim2 with Xcode 12.0.1
Use CentOS with LXD
Use ngrok with Docker
Use webmock with Rspec
Use WebJars with Gradle
Generate JavaScript with Thymeleaf
Use jlink with gradle
Use aggregate queries (Count) with Azure CosmosDB Java SDK
I dealt with Azure Functions not working in Java
Use Lambda Layers with Java
Use GDAL with Python with Docker
Use pfx certificate with Okhttp3
Use Bulk API with RestHighLevelClient
Use SDKMAN! With Git Bash
Create Azure Functions in Java
Use multiple databases with Rails 6.0
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
Use Spring JDBC with Spring Boot
Use Ruby with Google Colab
Use SpatiaLite with Java / JDBC
Use log4j2 with YAML + Gradle
[Docker] Use whenever with Docker + Rails
Use PlantUML with Visual Studio Code
Use Basic Authentication with Spring Boot
Use java with MSYS and Cygwin
Implement text link with Springboot + Thymeleaf
Use constructor with arguments in cucumber-picocontainer
Use Microsoft Graph with standard Java
Use PostgreSQL inet type with DbUnit
Why use orchestration tools with Docker
Use bootstrap 4 with PlayFramework 2.6 (no CDN)
Let's use Amazon Textract with Ruby
Use Git with SourceTree and Eclipse
Use JDBC with Java and Scala.
Use DataDog APM with unsupported frameworks
How to use mssql-tools with alpine
Use database user-defined functions from JPQL
Beginning with Spring Boot 0. Use Spring CLI
Authentication / authorization with Spring Security & Thymeleaf
Use cuda11.0 with pytorch using Docker