Ebooks

Spring Boot first web application

Spring Boot first web application tutorial shows how to create a simple Spring Boot web application. The current trend is to launch Spring Boot applications from an executable JAR. (See SpringBootServletInitializer tutorial for an example of a traditional WAR deployment.)

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

Spring Boot web application example

The application shows a message and today's date. The message is retrieved from an appplication's property.

pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           └───controller
│   │                   MyController.java
│   └───resources
│       │   application.properties
│       └───templates
│               index.html
└───test
    └───java

This is the project structure.

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>springbootfirstweb</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.1.1.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-thymeleaf</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 build file. The spring-boot-starter-web is starter for building web, including RESTful, applications using Spring MVC.

The spring-boot-starter-thymeleaf contains the Thymeleaf template engine. When Spring Boot detects this starter, it automatically configures Thymeleaf for us.

The application is packaged into a JAR file, which contains an embedded Tomcat web server.

resources/application.properties
application.message: Hello there

The application.properties file contains various configuration settings of a Spring Boot application. We have one custom message option.

com/zetcode/controller/MyController.java
package com.zetcode.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDate;
import java.util.Map;

@Controller
public class MyController {

    @Value("${application.message}")
    private String message = "Hi there";

    @GetMapping("/")
    public String index(Map<String, Object> model) {

        model.put("now", LocalDate.now());
        model.put("message", this.message);
        return "index";
    }
}

This is the controller class for the Spring Boot web application. A controller is decorated with the @Controller annotation. The controller has one mapping. The mapping resolves to the index.jsp, which is located in the WEB-INF/jsp directory.

@Value("${application.message}")
private String message = "Hi there";

We inject a value from the application.properties into the message variable.

@GetMapping("/")
public String index(Map<String, Object> model) {
    
    model.put("date", new Date());
    model.put("message", this.message);
    return "index";
}

The @GetMapping annotation maps a GET request with the / path to the index method handler. A model is created and filled with data. The model is a Map interface, which allows for the complete abstraction of the view technology.

com/zetcode/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);
    }
}

The Application sets up the Spring Boot application.

resources/templates/index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home page</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<p th:text="'Date: ' + ${now}"></p>
<p th:text="'Message: ' + ${message}"></p>

</body>
</html>

The index.html displays two values: the current date and the received message. Both values are passed to the template via the controller.

$ mvn spring-boot:run

We run the application. Now we can navigate to localhost:8080 to see the application message.

In this tutorial, we have created our first Spring Boot web application. You might also be interested in the related tutorials: Introduction to Spring web applications, Standalone Spring applications, FreeMarker tutorial, Java tutorial, Spring Boot submit form, Introduction to Spark, or Introduction to Stripes.