Spring Boot
RESTful API
HTML
Controller
Web Development

How to return an HTML page from a RESTful controller in Spring Boot?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Spring Boot is a powerful framework that simplifies the development of Java applications, particularly in creating stand-alone, production-grade Spring-based Applications. One of the common tasks in web application development is returning HTML content to the user. This task can be accomplished efficiently using a RESTful controller in Spring Boot. This article explores the steps required to return an HTML page via a RESTful controller, explaining the technical aspects and providing examples for clarity.

RESTful Web Services in Spring Boot

REST (Representational State Transfer) is an architectural style that provides standards between computer systems on the web, making it easier for systems to communicate with each other. In Spring Boot, RESTful web services are designed to be stateless and use HTTP methods explicitly.

Key HTTP Methods

  • GET: Request data from a server at the specified resource.
  • POST: Submit data to the server.
  • PUT: Update data at the specified resource.
  • DELETE: Remove data from the specified resource.

Returning HTML from a Spring Boot REST Controller

In a typical Spring Boot application, controllers return data in the form of JSON. However, there might be scenarios where you need to return HTML content. The following sections guide you through the process of setting up a Spring Boot application that returns HTML from a RESTful controller.

Setting Up a Spring Boot Project

  1. Create a Spring Boot Project: You can use Spring Initializr (https://start.spring.io/) to generate a new project with essential dependencies, such as Spring Web.
  2. Include Thymeleaf: Thymeleaf is a highly popular templating engine that is well-supported in Spring Boot for rendering HTML views. In your pom.xml, add:
xml
1   <dependency>
2       <groupId>org.springframework.boot</groupId>
3       <artifactId>spring-boot-starter-thymeleaf</artifactId>
4   </dependency>

Creating a REST Controller

  1. Define a Controller: Create a new class annotated with @Controller.
java
1   import org.springframework.stereotype.Controller;
2   import org.springframework.web.bind.annotation.GetMapping;
3   import org.springframework.ui.Model;
4   
5   @Controller
6   public class HomeController {
7   
8       @GetMapping("/home")
9       public String homePage(Model model) {
10           model.addAttribute("message", "Welcome to the Home Page!");
11           return "home";
12       }
13   }
  1. Return HTML Page: In the method homePage, return the name of the HTML file. This will be resolved to src/main/resources/templates/home.html by default.

Creating an HTML Template

In src/main/resources/templates/, create a file named home.html:

html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>Home Page</title>
7</head>
8<body>
9    <h1 th:text="${message}">Static welcome message</h1>
10</body>
11</html>

Here, th:text="$&#123;message&#125;" leverages Thymeleaf's powerful templating capabilities to inject dynamic content into the HTML.

Application Configuration

Ensure your Spring Boot application has the following properties in application.properties or application.yml:

properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

These properties let Spring Boot resolve template files correctly into the application.

Summary Table

FeatureDescriptionExample
ControllerAnnotation to create REST endpoints.@Controller
HTML ResolutionThymeleaf resolves templates for HTML content.return "home";
TemplatingDynamic injection using model attributes.th:text="$&#123;message&#125;"
ConfigurationEnsures template prefix and suffix are set.spring.thymeleaf.prefix
DependenciesRequires Thymeleaf in pom.xml.Spring Boot Starter Thymeleaf

Additional Considerations

  • Error Handling: Implement error-handling mechanisms to provide meaningful error pages to the user.
  • Custom MVC Configuration: If required, configure custom settings by extending WebMvcConfigurer.
  • Static Resources: Serving images, CSS, and JS files should be placed in src/main/resources/static/.

Conclusion

Returning HTML from a RESTful controller in Spring Boot is straightforward with the right setup. By combining Spring Boot's flexible controller model with Thymeleaf's templating engine, you can serve dynamic, user-friendly web pages with ease. Understanding these foundational aspects will empower you to build rich, interactive applications in a seamless manner.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design