Spring Boot @Controller

Spring Boot @Controller tutorial shows how to use the @Controller annotation in a Spring application to build a web controller.

Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.

Spring MVC

Spring MVC is the original web framework built on the Servlet API. It is build on the popular MVC design pattern. MVC (Model-View-Controller) is a software architecture pattern, which separates application into three areas: model, view, and controller. The model represents a Java object carrying data. The view represents the visualization of the data that the model contains. The controller controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

Spring Framework 5.0 introduced a parallel reactive stack web framework called Spring WebFlux.

@Controller

@Controller annotation indicates that the annotated class is a controller. It is a specialization of @Component and is autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation. @RestController is a sibling convenience annotation for creating Restful controllers.

Spring Boot @Controller example

In the following application, we demonstrate the usage of @Controller. The application returns current data and time to the client.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── Application.java
    │   │           └── controller
    │   │               └── MyController.java
    │   └── resources
    │       ├── static
    │       │   └── index.html
    │       └── templates
    │           └── showMessage.ftl
    └── test
        └── java

This is the project structure of the Spring application.

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>SpringBootController</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.9.RELEASE</version>
    </parent>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>   
        
    </dependencies>

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

This is the Maven pom.xml file. The spring-boot-starter-parent is a parent POM providing dependency and plugin management for applications built with Maven. The spring-boot-starter-freemarker is a dependency for the Freemarker template engine. This dependency will also have the Spring MVC included in the project. The spring-boot-maven-plugin packages Spring applications into executable JAR or WAR archives.

MyController.java
package com.zetcode.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {
    
    @RequestMapping(value = "/getDateAndTime")
    public ModelAndView getDateAndTime() {
        
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String date_time = dtf.format(now);

        Map<String, Object> params = new HashMap<>();
        params.put("date_time", date_time);

        return new ModelAndView("showMessage", params);
    }
}

This is MyController. It responds to the request from the client. It finds out the current date and time and resolves the processing to the showMessage.ftl template, passing it data.

@Controller
public class MyController {

MyController is annotated with the @Controller annotation.

@RequestMapping(value = "/getDateAndTime")
public ModelAndView getDateAndTime() {

The getDateAndTime() method is mapped to the getDateAndTime URL pattern; it returns a ModelAndView, which is a holder for both Model and View in the web MVC framework.

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String date_time = dtf.format(now);

We get and format the local date and time.

Map<String, Object> params = new HashMap<>();
params.put("date_time", date_time);

The date and time string is added to the map of parameters.

return new ModelAndView("showMessage", params);

We return the ModelAndView. Since there is a Freemarker dependency in the POM file, Spring resolves processging to the showMessage.ftl template file, passing it the params object.

index.html
<!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>
            <a href="getDateAndTime">Get date and time</a>
        </p>
    </body>
</html>

This is the home page. It contains a link that calls the Spring controller. It is a static resource and is located in the predefined src/main/resources/static directory.

showMessage.ftl
<!DOCTYPE html>
<html>
<head>
    <title>Show message</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    
Date and time: ${date_time}    

</body>
</html>

The showMessage.ftl is a Freemarker template file. It is located in the predefined src/main/resources/templates directory. It outputs the date and time, using the ${} syntax.

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);
    }
}

Application is the entry point which sets up Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning. During the scanning process, the @Controller annotation is looked up and a Spring bean is created from the MyController class.

In this tutorial, we have shown how to use @Controller annotation in a Spring application. You might also be interested in the related tutorials: Spring Boot @RestController tutorial, Java Servlets tutorial, Spring Boot @ResponseStatus tutorial, Spring Boot @ExceptionHandler tutorial, Spring Boot upload file, Spring Boot @Component tutorial, Spring Boot @RequestParam tutorial, Java tutorial.