This article demonstrate: How to build a Spring Boot WEB applicaiton with Freemarker.
Why use the Freemarker in Spring Boot Web Application
As a relatively obsolete technology,By default, the Freemarker is not used as a template for web page rendering in Spring Boot 2, However, in the face of some old system upgrades written in Freemarker, you may also want to be able to configure support for Freemarker.
Next, let’s build a Spring Boot Web Application from scratch and then add support for Freemarker.
Development Environment
In tutorial, we use the following softeware environment, and all softwares are free.
Java: JDK 17 Oracle JDK 17, download it from Offical Website
IDE: IntelliJ IDEA 2021.3.1 Community, download it from Offical Website
Generate a Spring Boot Web Application Example
In Spring Boot Starter, fill in the basic configuration information(Artifact: todo-restful-service) of the project and the third-party components that need to be used in the project.
In this turorail, we suggest to choose:
- ‘Java’ as the language
- ‘Maven Project’ as the Project (type)
- the version of Spring Boot chooses the latest stable version 2.6.3.
- ‘Jar’ as the package (type)
- the version of Java choose Java 17
And choose the following dependencies:
- Spring Web
- Freemarker
After completed the above steps, click the “Generate” button to download the generated project basic package. Unizip it and open it with IntelliJ IDEA IDE.
Create a Spring MVC Controller
In Spring Boot Web Application, each HTTP request can be configured to respond with a corresponding method in the Controller. In this case, we built a Controller to respond to the root path.
Create a new package named controller and create a new class in the package named IndexController, as follows:
1 |
|
About the more information about spring mvc controller, you can refer the Offical Documentation
Create a Freemarker page
In src/main/template folder, create an new file, named: index.ftl. And fill the following content into it:
1 |
|
Configure Freemarker view
Rename the application.properties file in src/main/resources: application.yml, and add the following:
1 | spring: |
Run Web Application
Run the Web Application
If you run it in console, you can execute:
1 | mvn spring-boot:run |
If you use IDE tools, you can call maven in the IDE menu to run the application.
After the application is running, you can access the following URL via your browse.
1 | http://localhost:8080 |
You can see something like this in your browser
1 | Hello Freemarker! |
Download the Code
You can download the completed code from GitHub