Getting Started With The Spring Framework

A friendly Introduction Part I

Thulani Tembo
Developer Circle Lusaka
13 min readOct 31, 2018

--

With the rise in the number of people and organizations relying on APIs to serve their customers and achieve their organizational goals, there is high demand for web based systems more than ever. This is not an article about APIs so I’m not going to talk much about that.

In my journey as a Java developer, I had been looking for a way to create web applications in the language but without any guide from anyone, it was quiet a struggle until I joined a software development company where a workmate and a friend of mine introduced me to Spring, a Java framework for building web apps, it was the grandest day of my life. Now let me not bore you with the details of my relationship with Spring and get straight to the sweet stuff!

What is Spring?

The Spring Framework is an application framework and inversion of control container for the Java platform . The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE (Enterprise Edition) platform.

What can you do with spring?

In a nutshell, Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. Though so many other more, Spring capabilities can be summarized in the following few (Understand that there are many other things that we can do with spring I just thought it’d be cool to keep the list short and interesting).

  1. You can use Spring Framework for writing web applications.
  2. You can use Spring Framework for exposing RESTful services.
  3. You can use Spring Framework to secure your web applications.
  4. You can use Spring Framework for handling long running jobs.
  5. You can use Spring Framework for standalone java projects.
  6. You can use Spring Framework to convert your application into an executable.

In this 6 (six) part series of the Spring framework, we will be building a simple Blog application that will cover most of the basic elements of spring to get you geared up into building your own larger application. The series is structured as follows:

Part I: Introduction (This part) — Will introduce spring, as did above and it will introduce the project that we will be doing. It will go into installation, prerequisites, project setup, Introduction to Maven, and finally we will create a “Hello, World” web application in Spring MVC.

Part II: Project Design — Will cover the configuration of static files into spring and the designing of our simple interface.

Part III: Using MySQL With Spring — This chapter will introduce you to the various packages you need to install in order to use MySQL database with Spring.

Part IV: The Posts — This chapter will cover the creation of Entities, Repositories, Services, and Controllers in order to for you to get started on Spring’s MVC (In the meatime, do get started on reading about MVC).

Part V: User Authentication — This chapter will look at applying security to our application.

Part VI: Wrapping Up — Finishing the project, Compiling it down to an Executable Web App, them we’ll be done! :D

Prerequisites

Before we get started, make sure you have the following Installed:

  1. Java 1.8 (Recommended)
  2. Intellij IDE (Community version is free and suggested: get it here)
  3. MySQL Server 7.* or XAMPP/ WAMP which also comes with MySQL
  4. MySQL workbench for database Browsing incase you installed MySQL Server as a standalone server. (If you have XAMPP or WAMP you can skip this point)
  5. Google Chrome or Firefox web browsers.
  6. An active Internet Connection

Installation

I won’t got into the installation of the above mentioned prerequisites as I believe they’re pretty straight forward. So I will assume you have them set up and ready to go! We can proceed to Project Initialization! I’m excited! :D

Project Creation

The beauty about Spring applications is that there is not only one way of starting a project, but several and you can choose which ever suits you. One way is that we can initialize it directly from Intellij by using a plugin called ‘Spring Assistant’ which presents you with several options that you’d like to have in your application. In this series, will use an online service called ‘Spring Initializr’ to start our project, this option is faster and there is a small to no-possiblity of running into errors while starting you project.

Step 1: Project Initialization

Head on over to Spring Initializr, you will be presented with the following screen.

From the image above we will focus only the 3 fields labeled Group, Artifact, and Search for dependencies, the other three fields on top will be left as they are with their default values but if you see something else, make sure you use the values above (Maven Project, Java, and Spring Boot 2.0.6).

Further explanation on the fields we are using:

Group: uniquely identifies your project across all projects, so we need to enforce a naming schema. A group must follow Java’s package name rules. This means it must start with a reversed domain name you control. In our case we will use the group of com.devclusaka.

Artifact: Simply put, infers the name of the project.

Dependencies: This is the field in which we specify the packages/ dependencies that you wish to use in your projects. You can specify dependencies such as Database packages, Security packages, Social packages e.t.c. As soon as you start typing a package name, some suggestions will pop up the screen. For now we will only specify 2 packages, Web & Thymleaf.

The Web package is what will tell spring that we want to create a web application where as Thymleaf is a template engine that we will use to render web pages and other static files such as CSS, and JS files.

Once you have all that type up, you should have something like this:

Notice the Selected dependencies as Web and Thymleaf, make sure you have the same setup.

Finally we have our Group value as com.devclusaka, Artifact as myblog (project name) and Dependencies as Thymleaf and Web for now. Go on and click Generate Project. You will be prompted to download a zipped folder of the a “mini” project, save it in a directory of your liking and move on the next step.

Opening The Project in Intellij

Its time to fire up our favorite Java IDE and get to the good stuff. Open Intellij IDE to load up our project. The first screen should look something like this if you do not have any project open yet.

Intellij Launch Tab.

Once you launch Intellij, go on over to “open”, and navigate to the project we generated and extracted. The next screen should look something like this:

Navigate to the project we created on Spring Initializr.

One you’ve navigated to the project, select the project folder and hit OK to open the project.

Now here’s why I recommended that you install Intellij, once you hit OK, the IDE will open the project and It will start downloading the dependencies we specified on Spring Initializr onto your local machine for easier loading because by default, spring will try to look for the dependencies on your local server and when it has not found them, it will attempt to reach out to the remote server to retrieve those needed dependencies (We will look at how to get other dependencies without using Spring Initializr in a later chapter).

The download progress will appear on the bottom-right right corner as a progress bar and once you click on it, it will pull up something like this:

This shows the packaging that’s currently being installed and as well as the repository (URL) that its coming from. Wait for it to finish then head on to the next step. :)

File Structure

Once the packages have finished downloading, we can expand the project folder like so below:

The structure of our newly created project.

The above image shows the structure of our newly created project. Now bare in mind the through the course of this tutorial, we will focus mostly on the src directory and the pom.xml in the root of the project.

pom.xml — What is a POM? A Project Object Model or POM is the fundamental unit of work in Maven (read further on Maven Here). It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/test/java; and so on. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.

Some of the configuration that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified.

src/main/java — This is the source directory for all of our java files. We will be creating packages in this directory and then creating Java files in those packages. An example of a package is the main package com.devclusaka.myblog, as you can observe this package only contains one file called MyBlogApplication.java and when we open this file, we see the following code:

package com.devclusaka.myblog;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

At this point, I would like to introduce you to a very important part of Spring or Java in general called Annotations. In the code above, we have one annotation @SpringBootApplication, annotations have been a very important part of Java and it’s been there from the time of J2SE 5.0. All of us might have seen annotations like @Override and @Deprecated in our application code at some place or another.

What are Annotations?

One word to explain Annotation is Metadata. Metadata is data about data. So Annotations are metadata for code. For example look at following piece of code.

@Override
public String toString() {
return "This is String Representation of current object.";
}

I have overridden the toString() method and used @Override annotation in above code. Even if I don’t put @Override, code works properly without any issue. So what’s the advantage and what does this annotation stand for? @Override tells the compiler that this method is an overridden method (metadata about method) and if any such method does not exist in parent class, then throw a compiler error (method does not override a method from its super class). So in simpler terms, we could simply say annotations are used to briefly describe what a method or class is about or what kind of information it contains. In this tutorial, the common annotations that we will use are Controller, Service, Repository, and Entity.

Back To the Main Course!

Ok! enough of that! Back to the tutorial now. Ok so we were here:

Main class annoted as @SpringBootApplication.

Basically what the @SpringBootApplication tells java is to run the application as Spring application, If we were to remove the annotation and the SpringApplication.run(MyblogApplication.class, args); statement from the main method, the app would be run as a normal Java application. This file is the entry point for any spring app the you will work on, though the file and class name will vary according to the names you give to your projects.

src/main/resources — This directory contains two directories namely static where you will dump your static files such as Images, CSS, and JS files, it also contains the templates folder in which you will dump web files (HTML files).

One more important content of the resources directory is a file called application.properties, this is a configurations file where we can define things like the application port number, database connections, and a lot more we will discover throughout the series.

Application.properties.

If you open this file, you’ll notice its empty, we will fill it with a whole lot of not so much stuff later in the series. :)

Hello, World! Hello, First Controller!

Ok, I’m confident enough that we’ve covered quiet some huge ground by now, time to make our first running web app in spring, and yeah obviously its a Hello, World app :) .

Step one: Navigate to src/main/java then right-click on the com.devclusaka.myblog then hover over to the New option, finally hover over to and click Package as illustrated below:

Creating Controllers Package.

Once Package is clicked, it should bring a new pop-up field where it asks for the package name, give it the name Controllers then hit OK. By now, a new package Controllers would have been created under the main package.

Controllers Package Created.

What the heck are Controllers?!

In Spring framework, all the requests sent by the dispatcher servlet normally directed to a controller class. This controller class is mapping those requests to each process & execute the requested inputs. It is from controllers where we map templates to specific URLs, it is also from controllers where we parse data between the repository and templates.

Creating Our First Controller Class

To create our first Controller class, all we have to do is Right-Click on the newly created Controllers package, hover over to New, now this time hover over to Java Class, conveniently it should be the first option. You will be presented with the following option:

Create New Class.

Now, go on and give the class the name of HomeController, keep the cases as I have given it like so:

Filler Controller.

For now, leave the Kind option as Class. Hit OK. Your new class should be created now and it looks something like this:

package com.devclusaka.myblog.Controllers;
public class HomeController {

}

And you updated Controllers package should look something like this now:

Created HomeController.java

Open your HomeController files and update it to look like this:

package com.devclusaka.myblog.Controllers;

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

@Controller
public class HomeController {

@GetMapping("/")
public String homePage(){
return "index";
}

}

What we’ve just added to HomeController

  1. @Controller — As mentioned before, this annotation simply tells Java to treat the HomeController class as a Controller. Controllers can send and receive HTTP requests such as GET, POST. There is another type of controller annotation denoted as @RestController which is mostly used when creating RESTful APIs but we won’t get into that.
  2. @GetMapping — This annotation tells java that this homePage() method accepts HTTP GET requests. The annotation takes in one parameter as observed in the code, the parameter is the URL as a String on which the GET requests will be going through.
  3. homePage Method — This is simply a public method that returns a String, the string value we return is simply the HTML template which we have not created yet but worry not, we’ll get there shortly. :D

The beauty about working with Intellij is that you will not have to worry about manually importing packages anymore because it is smart enough to import them automatically and if it not sure from which library to import them, it will ask you to choose, so don’t worry much about the two imports on the second and third line of code.

Creating The HTML Template

Now that we’ve got our first controller all set up and ready to use, we should now create our landing page.

Switch directories to src/main/java/resources and right click on templates, hover over to New, then click on HTML File. You should be presented with this screen:

In the last Image, we are provided with an input box asking for the HTML file name, now remember that in our container, we expect to return a template called index. That’s what we will name our template, like so:

There is no need to specify the file extension when creating our file because intellij will do that for as as suggested by the Kind field. Click OK!

At this point, Intellij will have create the html file for you and also added some started code, the full file will look like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

</body>
</html>

The file is created under src/main/resources/templates/index.html.

index.html created.

Now, go on and update index.html to something like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<h1>Hello, World! Hello, First Controller!</h1>

</body>
</html>

In the above code, we just add an <h1> tag that will be rendered in the browser once we run the app.

Running The App! Yay!!

We can run the app by either opening the main class under src/main/java/com.devclusaka.myblog/MyBlogApplication.java then right-clicking anywhere in the file then hovering over to ‘Run MyBlogApplication’ or by clicking the green play icon in the top-right corner within Intellij.

One the App finishes building, you should see something like this in the Intellij console:

App is running!!!!!!!!

from the last two lines we can see that our server started on Port 8080 and that the app is running. Now, fire up your favorite browser and head on over to localhost:8080 you should see this screen:

Success! Yesssss!!!

Conclusion

Through this introduction, we got introduced to Spring MVC and a few things it could be used for, though there is a lot more. We went on to creating our first Spring application and I guess you might have noticed that by default, Spring apps run on Tomcat server which already comes with Spring so your apps are always ready for deployment the moment you start them.

I hope this introduction has been helpful, if there are any question, suggestions or contributions please comment them below.

Be on the look out for part 2 in this 6 part series, we will be building a simple blogging web app throughout the course so STAY TUNED!

--

--

Thulani Tembo
Developer Circle Lusaka

Developer | AI Enthusiast | Data Science Entusiast| Thinker