Create a Monolith app from scratch with Java Spring Boot (part 1)

an introduction to creating a blog application server using Java Spring Boot

Posted by Wazoo on January 10, 2019 · 13 mins read

A popular option for a server stack is Java Spring Boot. While it’s not exactly the new kid on the block, it does offer a mature functionality base to work from. Maybe you’ve only just returned to the Java scene, or maybe you’re wanting to give it a shot. I’ll try to help you get your Spring Boot feet wet, and hopefully you’ll start to see how Spring Boot operates.

Before you start

  • Ability to handle some basic Java. Enough to understand basic package structure, etc
  • Using the terminal / console window in Mac / Linux / PC.

Goals

  • Understand enough about Spring Boot to get a project up and running.
  • Work with basic MVC concepts.
  • Run one command that will start and host your blog server.

What is Spring Boot?

Part of the Spring Framework, which was initially released in 2002, Spring Boot is an attempt by the Spring Framework team to expose the benefits of Spring, behind an out-of-the-box core.

Spring Boot relies quite heavily on several principles, most of which you might have already encountered in other forms in other frameworks / server stacks.

Convention over Configuration

Originally made popular by the Ruby on Rails core team, this principle speaks to the notion that Spring Boot provides a quick-to-start, but opinionated framework. Because of this, you get a lot of functionality “by default”:

  • complete standalone Spring applications
  • embedded Tomcat server means no WAR file to configure and deploy
  • provide and expose production-ready features such as health checks and metrics
Model-View-Controller (MVC)

The Model-View-Controller (MVC) architecture for building web applications is one of the oldest patterns in computer science. The MVC architecture for web applications, is supported by the Spring MVC component of the Spring framework.

One example of this in Spring Boot terms: An HTTP request is sent to the embedded Java Servlet container (e.g., Tomcat, Jetty, etc…) The HTTP request is first intercepted by the controller written in Java. The controller returns a template (or JSP) which is rendered on the server and returned to the web browser as static HTML.

I’ll highlight the actual MVC code changes we make in this tutorial / series, so if that small explanation didn’t help you with visualizing MVC, hopefully I can clear that up.

Inversion of Control

In software engineering, Inversion of Control (IoC) speaks to an architecture pattern where the control of objects or portions of a program is transferred to a container or framework.

To explain it a different way, most traditional software is based around your code calling methods within another library. Inversion of Control is the reverse of this; the library instead calls your code.

Therefore, if we want to add or change the default behavior of the container or framework, we must usually extend the framework.

Installation

Instead of relying on any “starter wizard” in your favorite IDE, let’s go right to the source and generate our Spring Boot skeleton. The team put together an online generator at https://start.spring.io/.

  • Project: Maven project
  • Language: Java
  • Spring Boot: 2.1.6
  • Dependencies: Spring Web Starter, Thymeleaf, H2 Database, Spring Data JPA

Hit the Generate the project green button.

When the generated .zip file downloads, look for it in your regular downloads folder. It should be extracted to your project folder.

first run

With the .zip file extracted to a folder, open a terminal window and go into the same folder.

Let’s take a quick look at what’s generated for us.

.
├── HELP.md
├── blog.iml
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── blog
    │   │               ├── BlogApplication.java
    │   │               └── ServletInitializer.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    └── test
        └── java
            └── com
                └── example
                    └── blog
                        └── BlogApplicationTests.java

  • mvnw and mvnw.cmd are helpers for Apache Maven
  • pom.xml is our main Maven dependency list. I think of it as Java’s version of NPM’s package.json
  • src/main contains all our application source code modules
  • src/test contains any tests for our Java classes
  • src/main/resources/application.properties defines any Spring Boot configuration properties

Let’s go ahead and use the Maven helpers to create our first build.

./mvnw package

After a bunch of output to our console, the BUILD SUCCESS banner should appear.

running the server

To run the server, we just need to use Java to run the .war file that’s been built for us in the target folder.

java -jar target/blog-0.0.1-SNAPSHOT.war

Spring Boot contains an embedded Tomcat server, thus it will be started as part of the server startup.

When you see the Tomcat started on port(s): 8080 (http) with context path '' output message, then go ahead and open your browser to http://localhost:8080.

You should see some text, Whitelabel Error Page:

spring boot default whitelabel error

While not the most intuitive of messages, this does mean your Spring Boot server is ready for action!

You can stop the server at any time with Ctrl+C.

Spring Profiles and Application Properties

First things first. While we don’t yet have plans to put this blog application into “Production” for the rest of the internet, a common practice is to define an environment for specifying debug or developer-mode type of properties - such as the address of your database, database login and passwords, etc.

Spring gives you this ability via the concept of Profiles. You can define a Profile for development, and one for production.

Let’s go ahead and create a Profile for local development.

cd src/main/resources
touch application-dev.properties

// application.properties
server.port=8080

// application-dev.properties
server.port=9000

To help demonstrate how these profiles can be used in different environments, update both the application.properties and application-dev.properties files with the different server.port values.

Once you save both files, re-build the server.

./mvnw package

Note: the application properties files are copied into the resulting WAR file during the build, so when you make changes to any properties file, a rebuild must be done for the server to pick up the new changes.

To recap, if we don’t tell Spring Boot which profile we’re using when we start up, then by default the settings in application.properties will be used.

Let’s test this out with the help of the -Dspring.profiles.active command line parameter.

java -jar -Dspring.profiles.active=dev target/blog-0.0.1-SNAPSHOT.war

You should soon spot the log message: Tomcat started on port(s): 9000 (http) with context path ''

Now Ctrl+c to stop the server and re-start it with:

java -jar target/blog-0.0.1-SNAPSHOT.war

You should see the log message: Tomcat started on port(s): 8080 (http) with context path ''

This is fine and handy for us, but it would be nice if we could select a profile by default. In other words, maybe we want to be using the dev Spring profile for a while during some active development, but we don’t always want to remember what to type on the command line.

Let’s go back to src/main/resources/application.properties and add a property called spring.profiles.active:

// src/main/resources/application.properties

spring.profiles.active=dev

Now after rebuilding, we can just go back to:

java -jar target/blog-0.0.1-SNAPSHOT.war

And you’ll notice that we’re using the dev Spring profile upon server startup.

Adding a welcome page

Now we can turn to adding a default welcome page for our blog. Eventually we’ll add the display of our current blog posts, but let’s get a page in place first.

To reference the Model-View-Controller paradigm, a View (aka. HTML template) requires a Controller behind it. In turn, this Controller can then use and interface with any Model (aka. data) that we want to reference (in other words our blog post data).

Let’s create a Controller for this. Create a new file called src/main/java/com/example/blog/WelcomeController.java

// src/main/java/com/example/blog/WelcomeController.java

package com.example.blog.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class WelcomeController {

    @GetMapping("/")
    public String index() {
        return "welcome"; // this string name matches our template name 'welcome.html'
    }
}

Notice that we’re using the @Controller Spring Framework annotation, which identifies this module as a Controller.

The default path of any website is usually at / - eg. http://localhost:9000/ which is the result of a GET request from your web browser; which means we need to use the @GetMapping annotation to our default root.

We’re returning a String in the form of our View which is HTML markup defined in welcome.html.

Let’s create that template now. The default path which Spring Boot uses is in - src/main/resources/templates.

Create a file called src/main/resources/templates/welcome.html:

// src/main/resources/templates/welcome.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Blog</title>
</head>
<body>
    <h1>Welcome</h1>

</body>
</html>

Save, rebuild the server then re-open your browser to - http://localhost:9000.

You should now see the Welcome header text!

adding CSS support

With the welcome template being displayed, let’s add some support for CSS - it’s kind of handy for a web application.

For our views (aka. html templates), Spring Boot is using a library called Thymeleaf. Because of its nice integration with Spring Boot, there’s virtually no configuration to setup. We just add the dependency to thymeleaf in the pom.xml and Spring Boot will recognize it right away.

(Just another reminder about the benefits of convention over configuration.)

Static files such as CSS files, are added to the src/main/resources/static folder. Let’s create an additional folder called css and add a new file style.css.

//src/main/resources/static/css/style.css

h1 { color: cornflowerblue; }

Now we just need to update the welcome.html template for the new static file. As with all CSS references, just add it somewhere in the head section.

<link rel="stylesheet" th:href="@{/css/style.css}" />
<title>Blog</title>

Save, rebuild and run. The Welcome header should now be in cornflowerblue!

Continued in part 2

I’m going to stop here.

We’ll continue our progress in Part 2 of this tutorial. As you’re seeing, there’s definitely a lot of information, so I want to give you ample opportunity to play around with things. I want to make sure I’m going through a lot of the smaller details that I had to pick up on my own to fill the gaps of other tutorials I used at the time.