Home » Enterprise Java » spring » Boot » Spring Boot FreeMarker Configuration Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Spring Boot FreeMarker Configuration Example

Welcome readers, in this tutorial, we will implement the Freemarker configuration in a spring boot application.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases

1.1 What is Freemarker?

  • Freemarker is a Java-based template engine that separates the presentation layer with the business logic
  • It prepares the dynamic webpages in an MVC architecture
  • It offers
    • Dynamic loading of webpages with template language
    • Localization and Internationalization (i10n and i18n) support
    • Reusability and adaptable data-model
Spring Boot FreeMarker Configuration - Flowchart Diagram
Fig. 1: Flowchart Diagram

Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot.

2. Spring Boot FreeMarker Configuration Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring Boot FreeMarker Configuration - Application Structure
Fig. 2: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring Boot FreeMarker Configuration - Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.

Spring Boot FreeMarker Configuration - Project Details
Fig. 4: Project Details

Select the Maven Web App archetype from the list of options and click next.

Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.springboot.freemarker</groupId>
	<artifactId>Springbootfreemarkerconfigurationtutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Spring Boot and Freemarker. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.springboot.freemarker</groupId>
	<artifactId>Springbootfreemarkerconfigurationtutorial</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>

	<name>Springboot Freemarker configuration tutorial</name>
	<url>http://maven.apache.org</url>

	<!-- spring boot parent dependency jar. -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.2.RELEASE</version>
	</parent>

	<dependencies>
		<!-- spring boot web mvc jar. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- spring boot freemarker jar. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>
	</dependencies>

	<build>
		<finalName>Springbootfreemarkerconfigurationtutorial</finalName>
	</build>
</project>

3.2 Application Properties

Create a new properties file at the location: Springbootfreemarkerconfigurationtutorial/src/main/resources/ and add the following code to it.

application.properties

# Application configuration.
server.port=8102

# Freemarker configuration.
spring.freemarker.template-loader-path= classpath:/templates
spring.freemarker.suffix= .ftl

3.3 Java Classes

Let’s write all the java classes involved in this application.

3.3.1 Implementation/Main class

Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.

Myapplication.java

package com.springboot.freemarker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Main implementation class which serves two purpose in a spring boot application: Configuration and bootstrapping.
 * @author yatin-batra
 */
@SpringBootApplication
public class Myapplication {

	public static void main(String[] args) {
		SpringApplication.run(Myapplication.class, args);
	}
}

3.3.2 Controller class

Add the following code to the controller class designed to handle the incoming requests. The class is annotated with the @Controller annotation to return a template view.
Freemarkercontroller.java

package com.springboot.freemarker.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value= "/freemarker")
public class Freemarkercontroller {

	/**
	 * Method to display the index page of the application.
	 * @param name
	 * @return
	 */
	@GetMapping(value= "/welcome/{name}")
	public ModelAndView welcome(@PathVariable(value= "name") String name) {
		ModelAndView model = new ModelAndView();
		model.addObject("name", name);
		model.setViewName("welcome");

		return model;
	}
}

3.4 Freemarker Templates

Create a new template file at the location: Springbootfreemarkerconfigurationtutorial/src/main/resources/templates/ and add the following code to it.

welcome.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greetings</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<h2 class="text-center text-info">Spring Boot Freemarker Tutorial</h2><hr/>
		<h4>Hello ${name}!</h4>
	</div>
</body>
</html>

4. Run the Application

As we are ready with all the changes, let us compile the spring boot project and run the application as a java project. Right click on the Myapplication.java class, Run As -> Java Application.

Spring Boot FreeMarker Configuration - Run the App
Fig. 7: Run the Application

5. Project Demo

Open your favorite browser and hit the following url to display the index page of the application.

http://localhost:8102/freemarker/welcome/world

Server name (localhost) and port (8102) may vary as per your tomcat configuration. Make note; world is a path param and can be changed for the testing purposes.

Spring Boot FreeMarker Configuration - Welcome Page
Fig. 8: Welcome Page

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to create a Spring Boot application with Freemarker template. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of configuring the Freemarker template in a Spring Boot application.

Download
You can download the full source code of this example here: Spring Boot FreeMarker Configuration Example
(+1 rating, 1 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of