Overview of This Lesson

Refresh this page because I am probably still making changes to it.

This lesson shows you how to create your first Spring Boot Project. You'll learn what all the different parts of a basic Spring Boot project are for and what files go where.

Review

Pre-requisites

It is assumed that you have installed an IDE that allows you to create Java Web Applications with Spring Boot. My demonstrations use Eclipse with Spring Tools.

Creating Your First Project

We'll start off with a basic project that will allow us to test our installation. First, there are a few important terms and concepts to consider:

In "real life", you will want to ensure your applications are easily searchable and also have a unique identifier. The standard identifier for a Maven project, which is also called its "coordinates" is the project's group name, followed by its artifact name, followed by its version number.

So in our pet store example, a unique ID for a particular build might be backwards.domain.petstore:Inventory:1.3.4. You don't actually need to worry about the unique ID for projects in this course, but it's helpful to understand why those 3 pieces of information are important!

Note also that a project has a package name. A project's package name is the root package for that particular project. For example, the online store could have a package name of backwards.domain.petstore.shop and the inventory application could have a package name of backwards.domain.petstore.inventory.

Creating the Project in Eclipse

Now that we have have a basic understanding of project characteristics such as group name, artifact name, and package name, we can create a new project.

  1. In Eclipse, select from the menus File > New > Other.
  2. Scroll through the list and look for the "Spring Boot" category. Open it, and select "Spring Starter Project". Alternatively, you can just type "spring" in the Filter text field, which is probably faster. Once that's selected, click the NEXT button.
    spring boot category expanded and spring starter project selected, next button highlighted
    Select Spring Boot > Spring Starter Project and then click NEXT
  3. Now it's time to enter the project details. First, enter a name for this project. In the example I used "Testing", so you can use that for this first project if you wish. The project name will also default to this artifact name, which is fine.
  4. The Type should already be set to "Maven" and the Packaging should already be set to "Jar".
  5. Select your Java version e.g. 14 or whatever 14+ version you have. NOTE: there was a bug with a recent version of Eclipse: for "Java Version" it might list only 11 and 16, even if you have 14, 15, or later versions installed. Don't panic. Select the closest version number closest to the version you have if your version isn't there. Note that I have not yet tested this on a version above 15 (I am currently testing 17).
  6. Language should already be set to "Java".
  7. For our projects, the group name will be the same as the project's package name. For all your projects in this course, you should use the group name and package name
    ca.sheridancollege.yourlogin
    Where "yourlogin" is your own Sheridan login name. Make sure you use proper naming conventions e.g. ca.sheridancollege.flintst and NOT ca.sheridancollege.FLINTST, sheridancollege.ca.flintst or CA.sheridan_college.FlintSt: remember that standard package naming conventions are to use the domain name backwards, all lower-case, no symbols. NOTE: failure to follow these conventions for evaluated projects will result in penalties on your evaluation grade.
  8. As mentioned earlier, Artifact name will default to the project name, which is fine for this course.
  9. Version should be left alone. The default of "0.0.1-SNAPSHOT" simply means this is a "snapshot" version, which is any version that is a work in progress, still under development, not ready for release. Maven will not use a snapshot release as a dependency for another application (which is good, but not something we really care about right now).
  10. Description is simply a description of your project. I really don't care if you fill this in or not, I'm not going to look at it, so you can leave it alone if you want.
  11. Package name, as mentioned above, should be set to the group name. Copy and paste the group name if that is easier for you. In a "real" application, this might be different (as described above) but for this course, you can use the group name unless you're told to do otherwise.
  12. That's all you need to do: click the NEXT button.
    all of the items filled in as described above
    A basic set of project details
  13. On the next screen is where we will add the dependencies for our project. The list of items you select on this screen will change and grow as we learn more of the things we can do with Enterprise Java applications! For our first project, we'll keep it simple: we need to add the Spring Web dependency so we can create basic web applications, and the Thymeleaf dependency (which allows you to create dynamic pages using templates, but we'll learn the details in an upcoming lesson).
    • The easiest way to find a dependency in the list is to search for it: in the text field type "spring web".
    • The list below will filter out most of the items so that we can more easily see the item Spring Web. Check off this item.
    Adding the spring web dependency
    Locate the Spring Web dependency
  14. Repeat the previous steps to add the Thymeleaf dependency: search for "thymeleaf" and select Template Engines > Thymeleaf.
    Adding the thymeleaf dependency
    Locate the Thymeleaf dependency in the Template Engines category
  15. Repeat the steps one more time to add the Spring Boot Dev Tools in the "Developer Tools" category (this adds some convenient features, like refreshing the application on the server whenever we make changes and save our files).
    Adding the spring dev tools dependency
    Locate the Spring Web Dev Tools dependency in the Developer Tools category
  16. Next time, you'll notice that Spring Web and Thymeleaf appear near the top so they will be easier to find!
  17. Click Finish

You now have a project! Before we start coding, we need to understand the basic project structure.

Project Structure

You might have already noticed, if you expand the project in the project explorer, there are already a lot of files and "nodes" there. Understanding what these items are is important: Different parts of your application must go in specific places, or the application won't work properly.

The first 3 items you'll see in your project are actually logical directories: they're there for easy access because you'll be working with these three directories the most.

the various nodes in the project inside project explorer
Expand the project node for your project inside the Project Explorer

The other items in the list include:

It's worth talking a bit about the POM File (pom.xml). POM stands for Project Object Model. The POM is where you configure the different parts of your project's dependencies. For example, we have already added a dependency for Spring Web, so if you wanted to change the details of how Spring Web worked for this specific application, you can do that in the POM file. If you wanted to add another artifact to your application, you can add this dependency by coding an entry for it in the POM file.

The POM is written in XML (Extensible Markup Language, a sort of sibling or cousin of HTML). In Eclipse, you can open the pom.xml file and edit it directly, or you can view it in more of a graphical user interface. Let's give it a try:

Go to the project explorer and double-click the pom.xml file in your project.

You should see all the XML code that makes up the POM. You might even recognize some of the project configuration you set up when you created the project.

the pom.xml file's xml contents
The contents of the pom.xml file

Along the bottom of the window showing the pom file contents, click the Overview tab. This shows you the exact same information in a more graphical form. It's nice to have, if you're not a fan of reading/editing XML code!

the pom.xml file contents displayed with labels and input fields
The contents of the pom.xml file

Clicking the Dependencies tab will show you the dependencies in this project. Right now there are only 3 items: spring-boot-starter-web, spring-boot-starter-test, and spring-boot-starter-thymeleaf. The first is needed to create web-based enterprise projects using Spring Boot. The second is needed to test (e.g. using JUnit) our project. The third is for the Thymeleaf template engine, which allows us to create dynamic HTML pages.

this project's dependencies
The dependencies defined in the pom file

At times later in the course, you will need to go in and edit this file by adding dependencies, so don't be afraid of exploring the pom file!

When you're done exploring, close the pom.xml file.

Let's look at one more file. When you create a new spring boot project, it automatically creates an application class for you. You probably won't ever need to edit this file, but I want to look at it anyway in case you do decide to do something extra that requires you edit this file.

In your project explorer, expand the node src/main/java. Inside, you'll see your ca.sheridancollege.yourlogin (whatever "yourlogin" is) package. Expand the package, and inside, you'll see the file "TestingApplication.java" ("Testing" is whatever you named this project/artifact when you created it).

package ca.sheridancollege;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Testing1Application {

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

}

Your application class is the main starting point of this entire application: it starts up the whole application and configures it. You'll see that inside the main() method, there's a call to SpringApplication.run(). This statement starts up the application as a stand-alone app and loads everything the application needs.

One of the ways in which we can easily configure the different classes and methods of our application is by using annotations. Annotations are the items that start with the @ (at) symbol, and they're part of the various Java/Maven/Spring classes, so they need to be imported.

On line 6 you'll see the annotation @SpringBootApplication (it's import is on line 4). This annotation indicates that this application should do certain things that make our life easier, like auto-configure itself when you don't manually configure certain things like database connections. It also ensures that all the standard components are exactly where they're supposed to be.

When you're done, you can close the application class.

Let's add some things so we can actually run this application and make it do something! We'll start off with a couple of basic HTML pages.

Adding HTML Pages

HTML pages and other web resources go inside the src/main/resources node of your project. Inside that node, you'll see two other nodes: static, and templates.

To understand the difference between the /static and the /templates directories, let's add one HTML page in each:

  1. Expand the src/main/resources node so you can right-click on the /static directory.
  2. Select New > Other
  3. You can scroll down to the Web category and open it, then select "HTML File" but it's faster to just type in the filter text "HTML", then select "HTML File" when it appears.
  4. Once you've selected "HTML File", click the NEXT button.
  5. For "File Name:" type "staticPage.html".
  6. Go ahead and add some basic HTML to your page so that you know this is the html page inside the /static directory (and not the /templates directory).
  7. Save your changes.

Now repeat the steps above, but this time right-click on /templates, and call your HTML file "templatePage.html". As with the first page, add some HTML code to your template page so that you konw this is the page in the /templates directory, and not the other one.

Let's try our application so far and see how it works.

Running the Application

In the project explorer, right click your "Testing" project node and select Run > Run As > Spring Boot App. Alternatively, you can locate the "Run" button (green circle) in the button bar at the top of the window. Pull down the little arrow on it and select Run As > Spring Boot App.

showing the run menu
Select Run > Run As > Spring Boot App

Be patient. A console window should open at the bottom of the Eclipse IDE and it should be spewing forth some information. Eventually it will stop spewing, and the last line will say something like:

2021-05-07 16:51:30.067  INFO 13424 --- [           main] c.s.jollymor.TestingApplication          
    : Started TestingApplication in 4.904 seconds (JVM running for 6.738)

That means your application is now running!

Of course, it doesn't appear to do anything, but remember, this is a web application! So now, open up your browser and in the address bar type:

http://localhost:8080/staticPage.html

Your static page should load. If it doesn't load or you see an error, check that you typed the above URL correctly. Make sure if you called staticPage.html something else, that's what you use instead of staticPage.html.

static page output: a heading and some text
Output from loading the static page

If that's not the problem, go to the output console in Eclipse and see if there's a stack trace. You might be able to figure out the error from the stack trace, just based on your own experience in Java 1 and Java 2. If not, copy and paste the entire contents of your output window and send it to me in an email (you'll find my email contact info in SLATE), or find me on Discord and we can do a screen share, so we can figure it out.

Now try loading your other page:

http://localhost:8080/templatePage.html
template page output: a 404 error
When you try to load the template page, you see a 404 (not found) error.

When you try to load the template page, you get a 404 error. Why? We know the page exists! You could try editing the URL and adding /templates, but that won't help (notice we didn't use /static/staticPage.html when we loaded the static page, and it still worked).

This is how spring applications work: Anything in the src/main/resources/static directory is the web root of any static pages/files. If you went into Eclipse and added an /images sub-directory to /static and put an image in there, you could easily access that image in the browser as localhost:8080/images/picture.jpg.

However, as mentioned earlier, you can't access anything inside /template directly. You can only access it via a Controller. Let's find out what that means!

Go back to Eclipse and terminate the application: you should see a button with a red square in the button bar, and also in the console output window. Either one will do: click it to terminate or stop your application.

Adding a Controller

Recall that the Controller is part of the MVC design pattern, and it's job is perform tasks between the view and the model, to do the main processing parts of your application. Let's add a Controller.

Controllers should always go in their own package. In fact, all components will do this: controllers in a controller package, data access classes in a database package, etc. Expand src/main/java and right-click your ca.sheridancollege.yourlogin package, and select New > Package.

adding a sub package
You're going to add a controllers package to your root package

You'll be asked to enter the package name. After your login name, add the text .controllers.

add sub package name in the Name field, after the main package name
Add ".controllers" to your existing package name

If you happen to right-click on src/main/java instead, that's ok: just select New > Package and type the entire package name ca.sheridancollege.yourlogin.controllers

Once you've added the controllers package, right-click the .controllers package and select New > Class.

right click controllers package and add a new java class
Add a new Java Class to the controllers package

For the name of your class, enter MainController. This will likely be the name of your controller class for most examples and exercises. You don't need any constructors right now, so if that option is currently checked, you can uncheck it.

adding a new java class in the .controllers package called MainController
Make sure your controller is in the .controllers package and give it a standard, self-documenting class name.

A project can have more than one controller, (and we'll do that in a later lesson) but you generally have a "main controller" - the controller that does most of the work, or a controller that contains the more important tasks. Some developers call it "HomeController" and some will name it according to what the project or controller does. For example, a controller that mostly performs tasks with the inventory pages might be called "InventoryController". For your own practice, feel free to call the controller anything you like, as long as it's a standard class name that is self-documenting. In my examples, I'll probably always call it "MainController".

Once you've entered all the information for your controller class, click the FINISH button.

The first thing you need to do with this class is tell Spring that this is a controller class. Spring won't know this is your Controller unless you tell it. One of the cool things about Spring is that we can do this right in the code using Annotations (in the "old days" we had to add code to an XML configuration file, and that was tedious).

Go above the class header and add the @Controller annotation. This annotation identifies this class as a controller class (as opposed to a data repository, or a web service, or anything else).

package ca.sheridancollege.jollymor.controllers;

import org.springframework.stereotype.Controller;

@Controller
public class MainController {

}

So what goes in a Controller class, anyway? This is the code that executes when the user triggers an action in the View, or when a model update triggers some kind of action. The controller's job is to do all that behind-the-scenes code. For example, when the user clicks Submit on a form, the controller captures the input data and processes it.

If you've ever written a JavaFX application, you used the Controller class to contain all your event handlers. You'll find that a controller in a Spring application is pretty much the same thing!

Your controller is always going to consist of methods, and sometimes some private data members. The methods will execute when certain things happen; they're often referred to as handler methods because they handle, or deal with, specific events that might occur. The private data members are used to give us access to certain objects in our controller, but we won't look at those for a few lessons.

One of the most common things you'll have in a controller is one or more handler methods that loads a specific view that you've placed in the /templates folder! Recall that in our current Testing program, we're able to directly load anything inside the /static folder, but we aren't able to access anything inside the /templates folder. That's because you can't access anything inside /templates unless you've got a controller method that loads that file for you! Let's see how it works:

Inside your Controller class, add the following code:

@GetMapping("/test")
public String testing() {
    return "templatePage.html";
}

Here's an explanation of this code in detail:

So this handler method simply says, "when someone goes to the URL http://localhost:8080/test, load the page /templates/templatePage.html".

Try it! If you didn't stop your application earlier, you'll need to restart it (there's a "Relaunch" button in the button bar, about 4 buttons to the right of the Run button). If you stopped your application after the last test, just re-run it again by using Run > Run As > Spring Boot App (Actually, if you use the Run button up top, you can click on it's little arrow and it should now have an entry for running this Testing project - Eclipse remembers your past "run configurations" for you).

Go back to your browser and retype the URL http://localhost:8080/staticPage.html to make sure that still works.

Now edit the URL and type http://localhost:8080/test

NOTE: If you changed the pattern inside @GetMapping, you'll need to use that instead of "/test". For example, if you have @GetMapping("/foo") then your URL need to be http://localhost:8080/foo

You should see the output from your template page! If you see a 404 error, make sure your GetMapping() pattern matches what you typed in the URL, and make sure that the return statement in the handler method matches the name of your HTML page in the /templates directory. If that doesn't solve the problem, go back and make sure you followed all the steps above.

output from the template page
You should see the output from your template page.

If you see any 500-series error, there might be a stack trace in the output console in Eclipse that can be helpful. If you are unable to solve the problem, contact your professor and provide all the details, including all the output from the console window, proper screen shots, etc.

What happens when you just go to http://localhost:8080? Try it. Going to this address should load the root of your project. In a normal web project, this would load any index.html page by default. However, we see an error instead.

error output from loading the web project root
If you try to go to the web root at http://localhost:8080, you'll get a 404 error.

There are two ways you can fix this:

  1. If your main index page is a static page, then simply add an index.html page into the src/main/resources/static directory.
  2. If your main index page is a dynamic page, then add the index.html page into the src/main/resources/templates page and add a handler method that maps the root "/" to your index page:
    @GetMapping("/")
    public String index() {
        return "index.html";
    }

Exercise

Add a file to your current project's /templates called about.html. Add some content to your about page - whatever you like! I'll show you in a later exercise how to include images or an external CSS.

In staticPage.html, add a link that uses "aboutme" as the href e.g. <a href="aboutme">All About Me!</a>

In your controller, add a handler method that maps to /aboutme. The method should return the file name of your about page "about.html".

Run (or re-launch) your project. You might have to refresh the static page in the browser to see the link you added.

Click the All About Me! link and you should see your about page.