Home Java javaTutorial Using FreeMarker for Web template engine processing in Java API development

Using FreeMarker for Web template engine processing in Java API development

Jun 18, 2023 am 08:39 AM
freemarker java api web template engine.

With the rapid development of the Internet, the development of Web applications has become more and more common. To make web applications more readable and maintainable, developers often use web template engines for view rendering. In Java development, there are many popular web template engines, and FreeMarker is one of them.

This article will introduce the FreeMarker Web template engine and its use in Java API development, including its core features, configuration and its application in actual combat.

1. What is FreeMarker

FreeMarker is an open source Java template engine that uses a template-based method to generate static text or dynamic web pages. Its feature is the separation of templates and program code, which clarifies the boundaries between performance and logic, separates page rendering and business logic, and improves the readability and maintainability of the code. FreeMarker supports multiple template types such as text templates, XML templates, HTML templates, JSP tag libraries, etc., and can be integrated with a variety of web frameworks, such as Struts2, Spring MVC, etc.

FreeMarker has the following features:

  1. Separation of concerns: The template file only defines the display effect of the page and the interactive behavior of front-end users, without embedded business logic code.
  2. Strong type support: Compared with JSP, FreeMarker has strong type support capabilities, which can help us check type errors at compile time and reduce runtime errors.
  3. Various template file formats: FreeMarker supports the processing of multiple template file formats, including, but not limited to, HTML, XML, and JSON.
  4. Compatibility: FreeMarker can be integrated into various web frameworks and is widely used in SpringMVC, Struts2 and other frameworks.

2. Use of FreeMarker API

FreeMarker provides many APIs to use it to generate templates. Our initial call involves configuring FreeMarker to emit templates. Next, we show how to set up and use the FreeMarker API.

  1. Introducing FreeMarker’s dependency package

First, we need to add FreeMarker’s dependency in the project’s pom.xml file:

    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.31</version>
    </dependency>
Copy after login
  1. Configuring FreeMarker

To create FreeMarker or you need a configuration to tell it how to load the template, refer to the following code example:

Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setClassForTemplateLoading(YourClass.class, "templates");
Copy after login

Among them, VERSION_2_3_28 is the FreeMarker version number, setClassForTemplateLoading() Method sets the path for FreeMarker to load templates.

  1. Set the data model

Next, you need to set the input data of the template. In FreeMarker, this background is a Map, and this Map needs to contain all the data we want to use in the template. We can use the SimpleHash type to create this Map:

Map<String, Object> input = new HashMap<String, Object>();
input.put("title", "FreeMarker Example");
Copy after login

In this example, we added "title" as the key and "FreeMarker Example" as the value to the input.

  1. Load and render the template

Finally, we need to load the template and render the input data into the template, refer to the following code example:

Template template = configuration.getTemplate("example.ftl");
Writer out = new OutputStreamWriter(System.out);
template.process(input, out);
out.flush();
Copy after login

In this example, "example.ftl" is a template file. We use the configuration.getTemplate() method to load it, and the template.process() method to render the data in the input into the template, and finally output it through out.

  1. FreeMarker template syntax

FreeMarker template syntax defines template tags, built-in formats, and methods. Template markers are directives in templates, consisting of FreeMarker template code in a pair of ${} or <% %> tags.

The following are some FreeMarker markers:

  1. ${...}: FreeMarker expressions can contain any legal Java expression.
  2. <% ... %>: Contains original template tags.
  3. <@...>..: Indicates an aggregate template fragment.
  4. #...#list..#assign...#recover...#stop: The original tag for operating and controlling template instances.
  5. <#macro...>...<#nested>: Define a reusable template block.

3. Application examples of FreeMarker

Below we will demonstrate how to use FreeMarker to write templates in Java API development.

  1. Write template file

First, we need to write a FreeMarker template file, for example, test.ftl:

<html>
<head>
<title>${title}</title>
</head>
<body>
<h1>${title}</h1>
<ul>
<#list users as user>
<li>${user.name} (${user.email})</li>
</#list>
</ul>
</body>
</html>
Copy after login

In this example, we Use the ${...} tag to reference the data in the input, and use the <#list ...> tag to loop through users and get the name and email attributes from each user.

  1. Set the data model and load the template

Then, we need to set the data model, refer to the following code example:

Map<String, Object> input = new HashMap<String, Object>();
input.put("title", "FreeMarker Example");
List userList = new ArrayList();
userList.add(new User("Tom", "tom@example.com"));
userList.add(new User("Jerry", "jerry@example.com"));
input.put("users", userList);

Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
configuration.setClassForTemplateLoading(YourClass.class, "/templates");

Template template = configuration.getTemplate("test.ftl");
Writer out = new OutputStreamWriter(System.out);
template.process(input, out);
out.flush();
Copy after login

In this example, we A JavaBean class named User is created. When creating the Map, we use userList as the key and the List reference as the value, and add it to the input.

3. Summary

This article introduces the FreeMarker Web template engine and its use in Java API development. FreeMarker makes web application development easier while improving code readability and maintainability. By explaining the core features, configuration and application of FreeMarker in practice, we hope to help readers better understand and apply FreeMarker.

The above is the detailed content of Using FreeMarker for Web template engine processing in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Using Imgscalr for image processing in Java API development Using Imgscalr for image processing in Java API development Jun 18, 2023 am 08:40 AM

Using Imgscalr for image processing in Java API development With the development of mobile Internet and the popularity of Internet advertising, images have become an indispensable element in many applications. Whether it is displaying products, building social circles, or enhancing user experience, images play an important role. In applications, it is often necessary to perform operations such as cropping, scaling, and rotating images, which requires the use of some image processing tools. Imgscalr is a very commonly used image in Java API development.

What are the free API interface websites? What are the free API interface websites? Jan 05, 2024 am 11:33 AM

Free api interface website: 1. UomgAPI: a platform that provides stable and fast free API services, with over 100 API interfaces; 2. free-api: provides multiple free API interfaces; 3. JSON API: provides free data API interface; 4. AutoNavi Open Platform: Provides map-related API interfaces; 5. Face recognition Face++: Provides face recognition-related API interfaces; 6. Speed ​​data: Provides over a hundred free API interfaces, suitable for various needs In the case of data sources; 7. Aggregate data, etc.

How to implement image verification code in Java API development How to implement image verification code in Java API development Jun 18, 2023 am 09:22 AM

With the rapid development of Internet technology, in order to ensure system security, verification codes have become an essential part of every system. Among them, picture verification code is favored by developers due to its ease of use and security. This article will introduce the specific method of implementing image verification code in JavaAPI development. 1. What is picture verification code? Picture verification code is a way of human-machine verification through pictures. It usually consists of a random combination of pictures containing numbers, letters, symbols, etc., which improves the security of the system. Its working principle includes

Using GreenMail for email testing in Java API development Using GreenMail for email testing in Java API development Jun 18, 2023 pm 02:22 PM

Java API is a widely used development language for developing web applications, desktop applications, mobile applications, etc. In JavaAPI development, email testing is essential because email communication is one of the main communication methods in modern society. Therefore, developers need to use some tools to test whether their emails are functioning properly. This article will introduce an open source software called GreenMail, which can be used in JavaAPI development for email testing. Green

What are the common protocols for Java network programming? What are the common protocols for Java network programming? Apr 15, 2024 am 11:33 AM

Commonly used protocols in Java network programming include: TCP/IP: used for reliable data transmission and connection management. HTTP: used for web data transmission. HTTPS: A secure version of HTTP that uses encryption to transmit data. UDP: For fast but unstable data transfer. JDBC: used to interact with relational databases.

JAX-RS vs. Spring MVC: A battle between RESTful giants JAX-RS vs. Spring MVC: A battle between RESTful giants Feb 29, 2024 pm 05:16 PM

Introduction RESTful APIs have become an integral part of modern WEB applications. They provide a standardized approach to creating and using Web services, thereby improving portability, scalability, and ease of use. In the Java ecosystem, JAX-RS and springmvc are the two most popular frameworks for building RESTful APIs. This article will take an in-depth look at both frameworks, comparing their features, advantages, and disadvantages to help you make an informed decision. JAX-RS: JAX-RSAPI JAX-RS (JavaAPI for RESTful Web Services) is a standard JAX-RSAPI developed by JavaEE for developing REST

What is j2ee and what technologies it includes What is j2ee and what technologies it includes Apr 14, 2024 pm 09:06 PM

J2EE is a Java platform designed for developing enterprise applications and includes the following technologies: Java Servlet and JSPJava Enterprise Beans (EJB)Java Persistence API (JPA)Java API for XML Web Services (JAX-WS)JavaMailJava Message Service ( JMS)Java Transaction API (JTA)Java Naming and Directory Interface (JNDI)

How to implement docker container technology in java How to implement docker container technology in java Mar 08, 2024 am 10:19 AM

Implementation method: 1. Add the Docker Java API dependency to your project; 2. Create a Docker client; 3. Use the Docker client to create and start a Docker container.

See all articles