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:
- 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.
- 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.
- Various template file formats: FreeMarker supports the processing of multiple template file formats, including, but not limited to, HTML, XML, and JSON.
- 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.
- 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>
- 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");
Among them, VERSION_2_3_28 is the FreeMarker version number, setClassForTemplateLoading() Method sets the path for FreeMarker to load templates.
- 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");
In this example, we added "title" as the key and "FreeMarker Example" as the value to the input.
- 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();
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.
- 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:
- ${...}: FreeMarker expressions can contain any legal Java expression.
- : Contains original template tags.
- ..@>: Indicates an aggregate template fragment.
- #...#list..#assign...#recover...#stop: The original tag for operating and controlling template instances.
- ...#macro>: 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.
- Write template file
First, we need to write a FreeMarker template file, for example, test.ftl:
<html> <head> <title>${title}</title> </head> <body> <h1 id="title">${title}</h1> <ul> <#list users as user> <li>${user.name} (${user.email})</li> </#list> </ul> </body> </html>
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.
- 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"); ListuserList = 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();
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!

JavaAPI开发中使用Imgscalr进行图片处理随着移动互联网的发展和互联网广告的普及,图片已经成为了很多应用中必不可少的元素。无论是展示商品、构建社交圈、还是增强用户体验,图片都扮演着重要的角色。在应用中,经常需要对图片进行裁剪、缩放、旋转等操作,这就需要借助一些图片处理工具来实现。而Imgscalr则是一个JavaAPI开发中非常常用的图片

整合ThymeleafThymeleaf是新一代Java模板引擎,类似于Velocity、FreeMarker等传统Java模板引擎。与传统Java模板引擎不同的是,Thymeleaf支持HTML原型,既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果。同事,SpringBoot提供了Thymeleaf自动化配置解决方案,因此在SpringBoot中使用Thymeleaf非常方便。SpringBoot整合Thymeleaf主要可通过如下步骤1.创建工程添加依

随着现代应用程序的不断发展和对高可用性和并发性的需求日益增长,分布式系统架构变得越来越普遍。在分布式系统中,多个进程或节点同时运行并共同完成任务,进程之间的同步变得尤为重要。由于分布式环境下许多节点可以同时访问共享资源,因此,在分布式系统中,如何处理并发和同步问题成为了一项重要的任务。在此方面,ZooKeeper已经成为了一个非常流行的解决方案。ZooKee

随着互联网技术的快速发展,为了保障系统安全,验证码已经成为了各个系统中必备的一部分。其中,图片验证码依靠着它的易用性和安全性受到开发者们的青睐。本文将介绍在JavaAPI开发中,实现图片验证码的具体方法。一、什么是图片验证码图片验证码是一种通过图片进行人机验证的方式。通常由一张包含数字、字母、符号等的随机组合图片构成,提高了系统的安全性。其工作原理包括

springboot整合freemarker踩坑报错2021-04-2302:01:18.148ERROR9484---[nio-8080-exec-1]o.a.c.c.C.[.[.[/].[dispatcherServlet]:Servlet.service()forservlet[dispatcherServlet]incontextwithpath[]threwexception[Requestprocessingfailed;nestedexceptionisfreemarker.cor

随着互联网技术的发展,RESTful风格的API设计成为了最为流行的一种设计方式。而Java作为一种主要的编程语言,也越来越多地在RESTful接口的开发中扮演着重要的角色。在JavaAPI开发中,如何设计出优秀的RESTful接口,成为了一个需要我们深入思考的问题。RESTful接口的基本原则首先,我们需要了解RESTful接口的基本原则。REST即Re

JavaAPI开发中使用Byteman进行动态代码注入在日常的JavaAPI开发中,经常会遇到一些需要进行动态代码注入的场景。动态代码注入可以用于调试、测试和性能分析等方面。在Java开发中,Byteman是一个常用的工具,它提供了一种简单且灵活的方式来进行动态字节码注入。Byteman是一个开源的Java工具,它可以在Java

Java开发人员在进行API开发时,往往需要处理各种工具类,这些工具类可以节省开发时间并且提高代码的可复用性。Hutool是一个Java工具类库,提供了丰富的工具类和常用的算法,能够提高API开发的效率。Hutool支持Java8及以上版本,可以方便地用于各种场景,例如字符串处理、日期时间处理、加密解密、文件操作等等,以下就是一些常用的功能。字符串处理Hut


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
