Spring Boot automated controller

In this tutorial, we are going to show how to create simple automated controller in Spring Boot framework. Our application shows a simple page that displays current date. We use FreeMarker as template engine.

Spring is a popular Java application framework. Spring Boot is an effort to create stand-alone, production-grade Spring based applications without musch hassle.

FreeMarker is a server-side Java template engine for both web and standalone environments. Templates are written in the FreeMarker Template Language (FTL), which is a simple, specialized language.

Sometimes we do not need complex controller logic and just want to return a view. ViewControllerRegistry registers simple automated controllers pre-configured with status code and/or a view. Its addViewController() method maps a view controller to the given URL path (or pattern) in order to render a response with a pre-configured status code and view.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── Application.java
    │   │           └── conf
    │   │               └── MvcConfig.java
    │   └── resources
    │       └── templates
    │           └── index.ftl
    └── test
        └── java
            └── com
                └── zetcode
                    └── HomePageTest.java

This is the project structure. FreeMarker template files have .ftl suffix; they are located in the src/main/resources/templates directory by default. Spring Boot automatically configures FreeMarker when it finds the dependency in the Maven POM file. We also include a test file.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.zetcode</groupId>
    <artifactId>SpringBootAutoController</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>    
    
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>    
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>              

    </dependencies>    

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>            
        </plugins>
    </build>
</project>

The spring-boot-starter-freemarker is starter for building Spring MVC applications with FreeMarker. The spring-boot-starter-test imports necessary testing modules. The application is packaged into a JAR file.

MvcConfig.java
package com.zetcode.conf;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }
}

In the MvcConfig class we configure a view and a controller for the home page. Since we have FreeMarker in the Maven POM file, Spring Boot automatically configures FreeMarker as the template engine. So the index view is mapped to the index.ftl template file, which is located in the src/main/resources/templates directory.

index.ftl
<#assign now = .now>
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>Today is: ${now?string.short}</p>
    </body>
</html>

The index.ftl template file is the home page of the application. It displays current date.

<#assign now = .now>

Here we assign current date time value to the now variable.

<p>Today is: ${now?string.short}</p>

We print the date in the short format.

Application.java
package com.zetcode;

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

@SpringBootApplication
public class Application {

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

We set up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

HomePageTest.java
package com.zetcode;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HomePageTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testHomePage() throws Exception {
        this.mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(view().name("index"))
                .andDo(print());
    }
}

This is a test for the home page.

$ mvn spring-boot:run

We start the application.

$ curl localhost:8080
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>Today is: 4/30/17 1:36 PM</p>
    </body>
</html>

With the curl tool, we retrieve the home page.

In this tutorial, we have created a simple controller and view in Spring Boot without creating a specific controller class. We have used FreeMarker as template engine. You might also be interested in the related tutorials: Spring Boot Thymeleaf tutorial, Spring Boot FreeMarker tutorial, Spring Boot Swing integration tutorial, Introduction to Spring web applications, Standalone Spring applications, FreeMarker tutorial, or Java tutorial.