SoFunction
Updated on 2025-03-03

springboot How to render html through SpringTemplateEngine

To obtain the rendered HTML string separately to facilitate other operations, it can be implemented in the following ways. A common usage is through SpringThymeleafThe template engine renders the template as an HTML string instead of directly outputting it to the browser. This way you can perform other operations on the rendered string, such as saving to a file or further processing.

1. Render as a string using Thymeleaf

You can useThymeleafofTemplateEngineManually render the template as a string. Need to passTemplateEngineRender the template file and return the rendered HTML as a string. You can create a custom service to handle this requirement.

1.1 Add dependencies

In addition to Thymeleaf dependencies, you also need to ensure that Spring Web and Thymeleaf dependencies aremiddle:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

1.2 Custom service class rendering Thymeleaf template is a string

import ;
import ;
import ;
import ;
@Service
public class HtmlRenderingService {
    private final TemplateEngine templateEngine;
    public HtmlRenderingService(TemplateEngine templateEngine) {
         = templateEngine;
    }
    public String renderHtml(String templateName, Map&lt;String, Object&gt; variables) {
        // Create a context object        Context context = new Context();
        // Set the passed variable to the context        (variables);
        // Rendering the specified template as a string        return (templateName, context);
    }
}
  • ()The final HTML string will be rendered based on the provided template name and context variables.
  • variablesIt's oneMapObject, used to pass variables into templates.

1.3 The controller calls the service class to render HTML strings

You can call this service in the controller, render the template into a string, and perform the operations you want (such as return, save, log, etc.).

import ;
import ;
import ;
import ;
import ;
@RestController
public class HtmlRenderController {
    @Autowired
    private HtmlRenderingService htmlRenderingService;
    @GetMapping("/render-html")
    public String renderHtml() {
        // Assume that the hot resources and recommended resource data to be passed        HotResource hotResource = new HotResource("Hot Resource 1", "12345", "67890");
        Map&lt;String, Object&gt; variables = new HashMap&lt;&gt;();
        ("hotResource", hotResource);
        return ("resources", variables);
    }
}

In the above code, when you access/render-htmlWhen this interface is used, the controller will callHtmlRenderingServiceService willThe template is rendered as a string and returned.

1.4 Thymeleaf template file ()

You can use the same Thymeleaf template file as before for dynamic rendering, for example:

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Resource recommendations&lt;/title&gt;
    &lt;!-- Slight style --&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="container"&gt;
        &lt;div class="section"&gt;
            &lt;h2&gt;Hot resources&lt;/h2&gt;
            &lt;div class="item hot-resource"&gt;
                &lt;a th:href="@{/resource/hot(id=${})}" rel="external nofollow"  target="_blank" th:text="${}"&gt;Hot resources名称&lt;/a&gt;
                &lt;p th:text="'Resource ID:' + ${}"&gt;resourceID&lt;/p&gt;
                &lt;p th:text="'Hotspot record ID:' + ${}"&gt;Hot Spot RecordsID&lt;/p&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

2. Do other operations after rendering HTML

You can do any operation in the controller by obtaining the HTML string as mentioned above:

  • Return HTML string: Directly return the rendered HTML string to the front-end.
  • Save HTML file: Save the HTML string to a file on the server.
  • Pass to other services: You can send this string to another service or system.

For example, save the rendered HTML as a file:

import ;
import ;
public class HtmlFileWriter {
    public static void saveHtmlToFile(String htmlContent, String filePath) throws IOException {
        FileWriter fileWriter = new FileWriter(filePath);
        (htmlContent);
        ();
    }
}

Call this method in the controller:

@GetMapping("/save-html")
public String saveHtmlToFile() {
    HotResource hotResource = new HotResource("Hot Resource 1", "12345", "67890");
    Map&lt;String, Object&gt; variables = new HashMap&lt;&gt;();
    ("hotResource", hotResource);
    String renderedHtml = ("resources", variables);
    try {
        (renderedHtml, "/path/to/save/");
        return "HTML file saved successfully!";
    } catch (IOException e) {
        ();
        return "Failed to save HTML file!";
    }
}

Summarize

Through the above scheme, you can:

  • Dynamic rendering of HTML pages is a string.
  • Return HTML strings, save to file, or perform other processing as needed.

The way to render as strings with Thymeleaf is very flexible and is suitable for you to do more customizations.

This is the article about springboot rendering html through SpringTemplateEngine. For more related springboot rendering html content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!