Spring Boot @Controller
last modified July 6, 2020
Spring Boot @Controller tutorial shows how to use the @Controller
annotation in a Spring
application to build a web controller.
Spring Boot is a popular application framework to create enterprise application in Java, Kotlin, or Groovy.
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.
Spring Boot @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.
pom.xml src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── Application.java │ │ └── controller │ │ └── MyController.java │ └── resources │ ├── static │ │ └── index.html │ └── templates │ └── showMessage.ftlh └── test └── java
This is the project structure of the Spring application.
<?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>controllerex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <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.
package com.zetcode.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; @Controller public class MyController { @RequestMapping(value = "/getDateAndTime") public ModelAndView getDateAndTime() { var now = LocalDateTime.now(); var dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); var date_time = dtf.format(now); var params = new HashMap<String, Object>(); 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.ftlh
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.
var now = LocalDateTime.now(); var dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); var date_time = dtf.format(now);
We get and format the local date and time.
var params = new HashMap<String, Object>(); 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.ftlh
template file, passing it the params
object.
<!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.
<!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.ftlh
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.
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.
$ mvn -q spring-boot:run
After the application is run, we can navigate to localhost:8080
.
In this tutorial, we have shown how to use @Controller
annotation
in a Spring Boot application.