Thymeleaf, a REST Controller and Cloud Run

Abirami Sukumaran
Google Cloud - Community
5 min readMay 29, 2023

--

Spring Boot on Google Cloud: Part 2!

Thymeleaf logo

🍃 What is it?

When developing a full stack web application with Spring Boot, one popular choice for frontend development is to utilize the capabilities of Thymeleaf. Thymeleaf is a server-side Java template engine that seamlessly integrates dynamic content into HTML pages.

Thymeleaf offers a smooth development experience by allowing developers to create HTML templates with embedded server-side expressions. These expressions enable the dynamic rendering of data from the Spring Boot backend, making it easier to display the results of analysis performed by your services.

👧 How I would explain Thymeleaf to a 5 year old!

When we build an application with Spring Boot, we want to make it look nice and interactive for people to use. Thymeleaf is like a magic tool that helps us make it look pretty and do cool things. Thymeleaf lets us create special pages called templates, where we can put different parts of our application together. It’s like building with LEGO blocks! We can have a header, a body, and a footer. Each part can be special and change depending on what we want to show.

📚 Dependencies

To begin, ensure that you have the necessary dependencies for Thymeleaf in your Spring Boot project. You can include the Thymeleaf Starter dependency in your project’s configuration, either through Maven or Gradle (we will continue to use maven in our series).

Link to the previous part of the series.

In the pom.xml from our last example, we already have the thymeleaf dependency included at startup because we used the command below to create the Spring Boot project structure in the cloud shell terminal that lists thymeleaf as one of its dependencies:

curl https://start.spring.io/starter.tgz -d dependencies=cloud-gcp,web,lombok,thymeleaf -d baseDir=first-spring-boot-app -d javaVersion=11 -d bootVersion=2.6.4 -d type=maven-project | tar -xzvf -

If you did not include it in the beginning, you can make sure that the below dependency is present in the pom.xml dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

With the auto-configuration feature of Spring Boot, you shouldn’t have to do any further explicit configuration. You can place html files in resources/templates folder.

👨🏽‍💻 ️Simple Thymeleaf UI and a REST Controller

Before proceeding with the code changes, make sure you have the Spring Boot project structure created from last blog. If not, execute the command (curl command) in the previous section to create it.

Once you setup the Spring Boot project, let’s do some code changes to the project to create Thymeleaf templates and a REST controller. You will see how easy it is to set up the user interface and implement a quick GET method.

  1. Create index.html file in the resources/static folder with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Cloud with Spring Boot code sample</title>
</head>
<body>
<div>
<form action="/hello" method="get">
Enter Your Name
<input type="text"
name="name"
value="Dear User"/>
<input type="submit"/>
</form>
</div>
</body>
</html>

The html above submits the form to action “hello” in the controller.

2. Let’s add a controller that will render the template. Create a file called HelloController.java in the /src/main/java directory with the content:

package com.example.demo;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;

@RestController
public class HelloController {
@GetMapping("/hello")
public ModelAndView extractLabels(String name, ModelMap map) {
map.addAttribute("name", name);
return new ModelAndView("hello", map);
}
}

This controller has a single method called hello(). This method returns the name of the new template that should be rendered and passes the attribute named “name” to the html.

3. Create hello.html file in the resources/templates folder with the following content:

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
Dear <p th:text="${name}"></p>
Welcome to Google Cloud with Spring Boot and Thymeleaf code sample!!!
</body>
</html>

The html above displays the static text along with the value of the ${name} attribute that was sent from the controller.

Now, let’s run the application. From Google Cloud Shell console, make sure you change directory to point to the newly created project folder “first-spring-boot-app” using the command:

cd first-spring-boot-app

Run the following commands to build your code and run locally

./mvnw package
./mvnw spring-boot:run

If the build is successful, it will start the application and it will be available on port 8080. Play with your application:

Demo of the application

🚀Deploy your app on Google Cloud Serverlessly!

Cloud Run allows you to deploy containerized applications on Google Cloud in just a few clicks. Besides the awesome features like click to deploy, auto-scale and pay-per-use, it has more to help you build and deploy your applications in any language at any scale. Learn about it. If your app is Java based (Spring Boot for instance), you can containerize your app without the overhead of creating a Dockerfile by yourself using a utility called Jib in a simple cloud shell command.

  1. Enable artifact registry by running the command below in cloud shell terminal
gcloud services enable artifactregistry.googleapis.com
gcloud services enable contianerregistry.googleapis.com

It is recommended that you route your container registry traffic to artifact registry.

2. Run jib command below from Cloud Shell terminal to containerize your app

./mvnw com.google.cloud.tools:jib-maven-plugin:3.1.1:build -Dimage=gcr.io/$GOOGLE_CLOUD_PROJECT/first-springboot-ctr

3. Run command below from Cloud Shell terminal to deploy your app

gcloud run deploy first-springboot-app --image gcr.io/$GOOGLE_CLOUD_PROJECT/first-springboot-ctr --platform managed --region us-central1 --allow-unauthenticated

Now that is all you needed to get your app to do the cloud dance 💃! You should see the service URL in your cloud shell terminal as a https service.

Conclusion

Congratulations!!! By harnessing the powerful capabilities of Thymeleaf, you have successfully created a visually appealing and dynamic user interface for your first Spring Boot application, implemented a REST service with Spring Boot and learnt how to deploy your app serverlessly on Google Cloud with Cloud Run. REST for next!

--

--

Abirami Sukumaran
Google Cloud - Community

Developer Advocate Google. With 16+ years in data and software dev leadership, I’m passionate about addressing real world opportunities with technology.