Good Thymes with Spring Boot

Over the past few weeks I’ve been working quite a bit on my own personal pet project, mainly looking into ways that I can persist (store) data I’m collecting from the Transport for London (TFL) API, but also looking into ways in which I could efficiently present this data on the front-end to users.

This led to two new features in my code, firstly I implemented the Spring Data module to store search results in a local Mongo database and secondly I implemented a dynamic front-end using web templating (Thymeleaf). Out of this I’m going to write two separate blog posts on here, one on getting your Spring Boot app up and running with a local Mongo DB and this one, focusing on how to render data on the front-end using Thymeleaf.

In this post I will be using basic Spring Boot app we created in a previous post to demonstrate how to utilise Thymeleaf to provide dynamic templates for repeated use.  If you’re new to the idea of templating, by the end of this post you’ll notice that you’ll be able to create many front-end interfaces for your users without the need to create loads of separate HTML files! We’re aiming to re-use the same HTML files multiple times, that’s the main idea and beauty of using a web templating engine such as Thymeleaf!

What are we going to do?

  1. Add the Thymeleaf dependency to our projects’ pom.xml file
  2. Alter our existing controller code to pass data into a template HTML file
  3. Create a template HTML file to render content passed to it
  4. Add iteration to our template to loop through a list of data

Stuff you’ll need

A Spring Boot Application

I’ll be basing this post on modifying the project we completed in a previous post so either use git to clone that project down or complete the steps in that post to proceed.

IntelliJ Community Edition

You can download IntelliJ here for yourself, we only need the Community (free) Edition but if you happen to have the Ultimate Edition, that will work fine as well.

Let’s get to it!

The code for this blog post can be found on the ‘thymeleaf’ branch of my springBoot_StartingPoint project on GitHub. As mentioned above, the steps in this post are based directly on the basic app we built in the Suited & (Spring) Booted post but the general concepts are applicable to any Spring Boot application that is built with Maven.

1. Add the Thymeleaf dependency to our projects’ pom.xml file

Navigate to the pom.xml file of your project and add the thymeleaf dependency as shown in the screenshot below.

1.JPG

2. Alter our existing controller code to pass data into a template html file

Now that we’ve got all of the required dependencies, we can start modifying our existing code ready to pass data to a HTML file. The HTML file in question does not yet exist but we need to understand how our current code needs to work first before progressing on to that bit!

The first thing we need to do is open the SampleController.java class and make a few changes. The first change we need to make is to change the @RestController annotation above the class name, simply to @Controller. This will mean that our endpoint will no longer attempt to output literal values, but instead return a reference to a HTML file to render.  If this doesn’t make sense at the moment, don’t worry I’ll make sure I show and example of this in action at the end of the post, take my word on this just for now!

We also need to utilise a special type of object called a ‘Model’. This object will be used to contain any data (known as ‘attributes’) we want to send from our Java code to our front-end for rendering. Below is a screenshot of what I want your SampleController class to look like, make the alterations to your class accordingly and we’ll go through what this is doing exactly afterwards.

2.JPG

Now that you’ve gone through and edited your SampleController class accordingly you might already have an idea of how the Model object works but let’s make sure quickly.

As mentioned, the Model object is there to contain any bits and pieces you want your front-end HTML to display for you. To do this you can use the ‘.addAttribute(<reference>,<value>);’ method on your Model object, in the above example that translates to “model.addAttribute(“title”, “Home”);” for example.

You can also see that you’re able to add multiple attributes to a single Model object, so you can think of the Model object as a box that holds whatever your controller puts into it. This box can then be transported to a HTML file, where Thymeleaf can ‘unpack’ the attributes into the HTML template. To tell our controller where to send our Model object (‘where to transport our box of attributes’), we simply tell our method to return the name of the HTML file in which the Model object, and all of the attributes added to it, should be sent to.

You might be asking yourself, ‘but why is the Model object a parameter passed into the method rather than created inside the method?! and that is a great question, my simplistic answer is that you can consider each request providing its very own box for you to add attributes to then return back in the form of a response. So it’s like turning up at the supermarket with your very own shopping bag (Model object) and asking the kind shop assistant to go off and get you some bread and milk (your ‘request’), they get the bread and milk, then put it in the bag you provided (add it to your Model object), which is then handed back to you (their ‘response’). As a code example the above would look a little bit like this:

3.JPG

You’ll be glad to know that was the most complicated part to go over in this whole post, now that we understand how our newly modified controller works it’s all very straightforward from here on out!

3. Create a template html file to render content passed to it

In the previous step we altered our SampleController class to populate a Model object then return a String value of “index”. This string value directly relates to the name of a HTML file (without the .html extension), in our case the ‘index.html’ file. The first thing we need to do is create our very own index.html file in the correct place for Spring Boot to find it.

4.JPG

Under the src/main directory create a new folder called ‘resources’, then create a ‘templates’ directory under that, this is where your HTML files will call home. You’ll notice the resources file has a special icon, this shows that IntelliJ knows that this directory is a special area for resources to live in. To make this icon appear go to File -> Project Structure then click ‘Modules’ on the left hand side of the window.

From this point you need to use the central part of the window to navigate to the directory you want to flag to IntelliJ as a resources directory and click the ‘Resources’ button above the central window as shown below, then click OK when you’re done.

5.JPG

Now all we need to do is create a new HTML file inside the newly created resources/templates/ directory, right click the templates dir and click New -> HTML File, call it ‘index’ and press enter. You now have a HTML file with the same name as shown in the return statement of the controller we worked on earlier, it’s all coming together!

Open the newly created index.html file and firstly amend the meta tag with a closing ‘/’ as shown below. This just gets rid of an irritating error later on as for some reason IntelliJ forgets to add this in!

6.JPG

Now we’ve got that straightened out, proceed to edit your HTML file according to the screenshot below, we’ll go over each bit afterwards to make sure we’re clear on what each bit does.

7.JPG

If you’ve ever worked with HTML before, you’ll likely be wondering what these foreign ‘th:…‘ tags are all about, these are how thymeleaf renders content into the HTML template!

There are two main changes in that we’ve had to make, both using the ‘th:text’ notation. You’ll notice that in using this notation we use ${attribute_name} to access data passed into our HTML file. By now you should be able to put 2 and 2 together to figure out that these directly match the references we included when adding Java variables to the Model object earlier on. As a reminder, here is what we added in our SampleController earlier on, you can see that the first value of each attribute is referenced in the HTML, therefore we can imagine that the second value of each attribute is what will be returned to the user at runtime.

8.JPG

The best way to see all this in action is to run our application! Open up the Application class and click the green run button next to the main method then once your app has started up, navigate to http:localhost:8080/ in your browser to see your app using Thymeleaf in all of its glory as shown below!

9.JPG

At this point you might be be thinking ‘ok that’s great but you said we could use this template thing over and over?’, absolutely, let’s create another method in our controller to demonstrate this point. We’re just copying our original endpoint method for “/” and changing a few values, but still using the same HTML page so make sure you keep the return statement the same!

10.JPG

Now restart your app to use the additional ‘/hi’ endpoint added above and navigate to http://localhost:8080/hi to see the below output.

11.JPG

From our little experiment we’ve now proven that our one template HTML file can be used for different endpoints and purposes, great stuff! This is the aim of web template engines.

4. Add iteration to our template to loop through a list of data

Thymeleaf is much more advanced than just being able to pass text from Java to HTML, in their documentation they outline all of the possible functions you can use as well as providing loads of in-depth tutorials for you to play around with. For now I’d like to take you through one simple feature which I’ve found to be very useful, the ability to pass a list of items to a template and have Thymeleaf iterate over it.

In terms of a use case for iterating over a list of strings, I’ve used this to populate dropdown menus or bullet point lists on pages – as you can imagine it’s much more flexible to pass a list of options to a dropdown or list rather than have to edit to the HTML every time you add or remove options elsewhere!

Let’s pass a list of Strings from Java to Thymeleaf and make it render each item as an element (<li>) in a bullet-point list (<ul>). To do this, amend your SampleController class according to the below screenshot (including additional method to return a list of Strings).

12.JPG

You’ve likely noticed two things, firstly that we have a list of three Strings (Bacon, Eggs, Gofer) that we’re passing to our Thymeleaf template and secondly we’re only passing the list of strings to the “/” endpoint. Even though both of the endpoints use the same template. This is ok – if you decide not to provide variables that the template (i.e index.html) uses, it’ll just add null values, or as we’ll hopefully see in a while, it just won’t render that element of the page.

To visualise this, amend your index.html file to match the below and restart your application.

13.JPG

Here we’ve implemented the ‘th:each‘ statement, this simply translates to ‘do something for each element in a given list’. Thymeleaf will now busily create list items (<li>) in a bullet-point (unordered, <ul> list for each of the values that are contained in a given list referenced as ‘listOfStrings’. You should now be able to see why I think this is immensely useful, for one thing the contents of these lists (which could be dropdown menus or other listed items  in HTML) are dynamically managed according to a single ‘source of truth’ in your controller code, and secondly the HTML code itself is much cleaner, succinct and easier to read.

Running this in the browser will output as shown below. As you can see, both endpoints are still using the same HTML template, however only the “/” endpoint provides the list of Strings for the template to render so is therefore the only place which the bullet-point list will be shown.

14.JPG

 

That’s all for now

Well not quite, I promised to show you the difference in output of a @RestController over a @Controller annotated class so if you modify the annotation of your SampleController class accordingly to @RestController and re-run the application we will see the difference in the browser as shown below.

15.JPG

16.JPG

 

 

 

 

As you can see, the methods in the SampleController class now return the literal Strings “index”, rather than using these values as a reference to the HTML file you wish to utilise, so revert your code back to using the @Controller annotation and only use @RestController when you want to return raw data!

As always, if you have any questions, suggestions or corrections please feel free to comment below, any and all feedback is gratefully received! 🙂

Thanks for reading,

Mark

Advertisements

Dockerising Spring Boot – the easy way

Since my last post (Suited & (Spring) Booted) I’ve been playing around with my own pet project, trying to make it run in a Docker container so that I can quickly and easily deploy it whenever and (for the most part) wherever I like.

In this post I want to take you through the most simple and straightforward way I found of Dockerising a Spring Boot application, by modifying the app we made in the Suited & (Spring) Booted post. In fact this means of Dockerising an application is not just for Spring Boot applications, this is a general means of Dockerising any project that is built using Maven.

Note: Although I will be pointing out the steps involved in getting an app running in a docker container, this post won’t necessarily be a ‘beginners guide to docker’. If you are very new to docker and containers, it might be worth having a look at the official docs or Googling around for beginner-level tutorials to make sure you can get to grips with it.

What is Docker?

You may have heard of the term containerisation while googling ways to deploy your revolutionary new web application – this basically means that you intend to package absolutely everything your application needs into a single, independent, ‘container’.

In a nutshell, docker packages up everything the app needs to run independently, and enables you to deploy that as a single item onto an environment such as a web server, your own laptop, or wherever you might need it to run. It saves messing around setting up your deployment environments, which is especially useful if you want to deploy an application across many machines and don’t want to spend all week configuring each one ready for your app to run on!

To do this it goes through the following steps:

  1. Builds an ‘image’ of your application using a ‘Dockerfile’ to define the application’s environment needs
  2. Runs a ‘container’ representing your application based on the ‘image’ generated in the previous step
  3. (Optional) Pushes the image to a ‘docker image registry’ (imagine a ‘github’ sort of thing just for docker images) so it can be accessed by machines anywhere, not just locally/where the image was built
  4. Viola! That’s it.

Aside from step 3, I’ll highlight each of these steps as we go through this post and show you how they are accomplished. If you want to push your images to a remote docker registry (step 3), I would recommend getting to grips with creating an image locally and running it first, i.e. conquer the stuff in this post then google that bit (it’s dead easy).

What are we going to do?

  1. Add a new plugin to an existing Maven project in order for Maven to use Docker
  2. Create a Dockerfile for the application
  3. Build a Docker Image of our application
  4. Run a Docker container locally

Stuff you’ll need

Docker

Installation of docker is well documented on their official site so head over there and get yourself set up.

A Spring Boot Application

I’ll be basing this post on modifying the project we completed in the previous post so either use git to clone that project down or complete the previous post to proceed.

IntelliJ Community Edition

You can download IntelliJ here for yourself, we only need the Community (free) Edition but if you happen to have the Ultimate Edition, that will work fine as well.

Let’s get to it!

As mentioned, this will be based on the Spring Boot application we wrote in the previous post but this should work just fine for virtually any Spring Boot (Maven-based) project out there.

1. Add the docker-maven-plugin to the pom.xml

This step is pretty self-explanatory, below you can see how the build section of my pom.xml looks after adding the new docker-maven-plugin so make sure yours matches this!

blog1.png

Just to clarify, the ${project.x} tags relate to the <artifactId> etc tags that are specified by default at the top of the pom.xml when you create a maven project. the <dockerFileDir> tag specifies the location of your Dockerfile for this project, we’ll leave it pointing at the base directory of the project as in this example we’ll just create it there for simplicity.

In using this particular plugin, we also need to add an additional file to the root of our project called .maven-dockerignore as shown below. To the best of my knowledge, this prevents some form of ‘docker inception’ but I’m not 100% sure, all I know is, without this later stages will definitely fail so add it in now to save pain later. Don’t forget to add target/docker/ inside it. (Thanks to this awesome post for helping me solve this issue!).

Screen Shot 2017-10-15 at 11.49.48.png

2. Create a Dockerfile for the application

Now that we’ve updated Maven to enable the use of Docker we can get started on setting up Docker itself! The Dockerfile is the key component to defining what our application needs when it’s running, even including information such as the operating system it requires to run on!

Create a new file in the root directory of the project called ‘Dockerfile’, your project structure should now look similar to the below image.

Screen Shot 2017-10-15 at 11.33.22.png

Below is the information in which you can copy into your Dockerfile to get it to work, we’ll go over the main elements briefly after you’ve added it in.

Screen Shot 2017-10-15 at 11.36.42.png

These are the four main parts of the Dockerfile that we need to know about:

FROM – defines the OS that the application will run on. Alpine is the most lightweight Linux based operating system going so we’re using that to save making a needlessly bulky image. As you can see, this particular flavour of Alpine comes with the Java 8 JDK which is useful for us as we also need Java installed to run our Spring Boot application! You can search docker for available OS’s by typing docker search <searchterm> in terminal or by searching  the Docker Hub site.

ADD – this command will take a local file and bake it into the image you are building. In this example we are interested in taking the jar file of our application and storing it in the image simply named as app.jar. Without this step our application would never make its’ way onto the image that we’re generating! You can add whatever files you desire from your local machine onto an image.

ENV – sets any prerequisite environment variables that might be required during the running of the application.

ENTRYPOINT – think of this as “when I run the container, what should happen immediately?“, in our example we are stating that as soon as the container starts running it should use java to run the jar file that represents our application. A.k.a. run our application as soon as its container is fired up.

3. Build a Docker Image of our application

That’s pretty much all the hard work done. All we need to do now is run a Maven command in the terminal and we should be able to see a new docker image generated locally. In the terminal (at the project root) run ‘mvn clean install docker:build. This one-liner will re-download all dependencies for your project if required, compile your code, create the project jar file and then eventually build a docker image according to the Dockerfile which it can find at the location specified originally in the pom.xml! A lot of stuff going on for such a simple command!

Note: At first you might see an error similar to “[ERROR] DOCKER> Unable to pull ‘openjdk:8-jdk-alpine'” in the terminal, don’t panic, this just means that docker needs to get hold of a copy of Alpine OS so as we can build our image. Run docker pull openjdk:8-jdk-alpine in the terminal and you’ll be all set ready to run the previous command again with no issues!

Now in the same terminal window run docker images and you should see something similar to the below. Note that we have both the Alpine OS image downloaded locally as well as the image of our very own application.

Screen Shot 2017-10-15 at 12.02.52.png

4. Run a Docker container locally

Now that we have an ‘image’ of our application, all we need to do is run it! To do this from the terminal run docker run -d -p1234:8080 68b2546b4148. Let’s break that command down a bit:

docker run – pretty self-explanatory, this is the docker command to state that you are going to run a container based on a given image

-d – this states that you would like to run the container as a daemon process (i.e. in the background rather than rendering your terminal window useless while the container is running – try running without this flag and you’ll see what I mean!)

-p1234:8080 – defines the mapping between host port and container (application) port. The app that we built in the previous post we know runs on port 8080, what if there is something else using port 8080 on the machine we’re deploying the app to? In this case we would specify that anyone wanting to use the app would actually use port 1234, which would be routed to the correct port for our application, ahhhh crisis averted! When we access the app in just a moment, you’ll see this in action.

68b2546b4148 – the IMAGE ID that we saw when we ran docker images a moment ago, replace this number with the IMAGE ID of your application (not the Alpine OS image one) and that’s it!

If we now run docker ps which loosely translates to “what docker processes are running locally?”, we should see that our app is up and running in all its majesty as shown below. You can also see under the PORTS heading that any requests on our local machine to port 1234 are now being routed to port 8080 on our app, fantastic stuff!

Screen Shot 2017-10-15 at 12.18.00.png

So now, if we open up a new web browser window and navigate to ‘http:localhost:1234’ we should see our amazing application working in all of its glory.

Screen Shot 2017-10-15 at 12.20.34.png

That’s all for now

And that is it! There’s really nothing more to it unless you want to work on automating the steps shown above into a shell script. For an example of this you can check out the init.sh script I wrote for my little pet project which handles all of the above with an incredibly satisfying level of automation 🙂

As always, if you have any questions, suggestions or corrections please feel free to comment below, any and all feedback is gratefully received! 🙂

Thanks for reading,

Mark

Suited & (Spring) Booted

Since my last post (Getting Started with Spring) I’ve been able to learn a little more about Spring in general, but the most notable part of Spring that I’ve begun experimenting with is Spring Boot.

What is Spring Boot?

Spring Boot provides an efficient means of creating web applications as all-in-one, ready-to-run standalone apps. It does this by bundling all of the required elements together in a single application, it even includes a built-in server for you (such as Tomcat). This makes your applications much less reliant on the servers that you want to run them on while also making the process of developing your applications much more simple. Spring’s official website explains the concepts of Spring Boot in much more detail, so for the most part I’ll leave you to dive in to the nitty gritty over on their site in your own time. For now, just know that Spring Boot is designed as a way to build standalone  webapps that you can get up and running quickly and easily. In this post I’ll briefly go through the main steps of creating a simple Spring Boot application. Stick with me and by the end of this post you’ll see how simple it is to build and run your very own Spring Boot applications.

What are we going to do?

  1. Create a new Maven project
  2. Write a basic Spring Boot application
  3. Run the Spring Boot application!

Stuff you’ll need

IntelliJ Community Edition

If you’ve been reading any of my posts to date, you’ll know by now that I am a massive fan of this IDE for coding of any kind, Spring is no exception! You can download IntelliJ here for yourself, we only need the Community (free) Edition but if you happen to have the Ultimate Edition, that will work fine as well.

Java

Head to the Oracle website to download the latest version of Java for your machine as we’ll need this installed to compile and  run our Java code!

Let’s get to it!

For this post I am going to use the official Spring Boot Quickstart guide as this is the simplest means of getting up and running. While we go through the quickstart guide, I’ll show you how I refactored the official quickstart guides’ example to improve my own understanding. Hopefully this will not only help you with your understanding of how the individual elements of a Spring Boot app fit together, but will also result in you having an easy to understand template Spring Boot app that you can use for your own projects!

1. Create a new Maven project

Open IntelliJ and choose File -> New -> Project… then select the option for Maven from the list on the left hand side (it should be about halfway down).

Leave the Create from archetype option un-ticked and click next.

Give it a GroupId e.g. com.mark.springbootblog. This option isn’t too important, it’s mainly important only for enterprise-level project where you’d need to define the domain or team your app will fall under such as com.marksCompany.financeWebApp.

ArtifactID is the name you want to assign to your app type in something like springbooted and click next. In the following screen the Project Name will likely autopopulate with the ArtifactID you gave your project so just check it is set and that you’re happy with the location of where your project will be stored and then click Finish.

You should now be presented with a screen similar to the below.

blog1

2. Write a basic Spring Boot application

As mentioned, we’ll be using the official Spring Boot Quickstart guide so I’ll try not to repeat too much information, however I am aiming to walk you through the steps required to get there with the assumption that you’ve never used Maven or Spring Boot before just to prove that anyone, regardless of experience can create Spring Boot applications!

The quickstart guide provided by Spring is so simple that aside from creating a package and a new class, less than 20 lines of code and a few dependencies need to be added to a basic Maven project in order to get your first Spring Boot application up and running! However, in fiddling with Spring Boot a little bit, I’ve refactored their example into something that helped my personal understanding of how it all works a little bit better, so stick with me and hopefully my little walkthrough will help you out as well.

Hopefully you were able to create your basic Maven project successfully in the step above, if not go back and try again! If so, we need to a few things into the main project file (the pom file) before we dig into the actual code. So open up the pom.xml  file and add the parent section and a new dependency as shown in the image below.

blog2

Now that we have the required dependencies in place (e.g. org.springframework.boot – enables you the usage of spring boot libraries and features, simple right?), we can start writing code for our Spring Boot app.

Following along with Spring’s quickstart guide still, create a package (right click -> new -> package) under the src/main/java directory called ‘hello’, the structure of your project should now look similar to the image shown below.blog3

From this point on I’m going to start deviating from the official documentation. The changes in my version of the application are simply to separate elements of the application into their dedicated classes. This should make it more readable  and very straightforward to add your own code into if you wish later on.

Inside our new ‘hello’ package we’re going to create only two files (Java classes), the first one will contain the controllers and logic to handle requests received by our application, the second will be there to start (or ‘bootstrap’) our application.

blog5

You can create these new classes now and add the code to them in the next couple of steps to make life easier (right-click the hello package -> new ->Java Class). Once created,  your project structure should look similar to the image on the right. Don’t worry if the icon next to the class name looks different (see Application), this will change once all the code has been added into each of the classes we’ve just created.

1. SampleController.java

This class will be relatively similar to the one provided in the Spring’s Official Quickstart guide however it has a bit of code taken out of it. My version of this class is shown below.

new

The main difference in my version is that I have moved the main (‘public static void main’ ) method out of this class. Much like any other Java program in the world, Spring Boot associates this method as the main entrypoint of the application. Therefore it made sense to me to move it away from the actual inner workings of the application, this made it a little easier to read and if this were to be used as a starting point for a potentially much bigger project, it will now already slightly refactored and ready to add new functionality in with relative ease.

The SampleController class now only focuses on one job, handling requests and executing the required logic. Simple!

Aside from that, there are some annotation differences (the yellow bits starting with ‘@’) on the ‘home’ method. This is for simplicity and understanding more than anything, now the method reads very simply as:

‘if we receive a HTTP request to the endpoint “/”, e.g. http://localhost:8080/, then return a response containing the String “Hello World!”‘

2. Application.java

So, now for the main entrypoint of the application, the mythical ‘public static void main’ method, known and loved (probably) by Java developers around the world. This is a very simple class as shown in the image below. (Ignore most of the icons next to the line numbers, the only icon of significance is the green ‘play’ button looking one on lines 7 and 9).

blog6

Most of this class is fairly self-explanatory. As mentioned above this is the main entrypoint of a Spring Boot application so the annotation above the class name ‘@SpringBootApplication’ is self-explanatory. The ‘main’ method within this class uses SpringApplication.run(…). And that’s all there really is to it, the application will now be able to bootstrap itself ready for use whenever you need it to.

3. Run the Spring Boot application!

This is even easier than any of the previous steps, open up the Application.java class and click on either of the green arrows on line 7 or 9. The run window at the bottom of the IDE should come to life with the Spring logo and eventually tell you that the application is running as shown below. If it fails to start, open the terminal tab at the bottom of the screen in the IDE and type ‘mvn clean compile’ and try to run it again.

blog7

The output shown above tells us a few things about our app, most notably:

  • “Tomcat initialized with port(s): 8080 (http)” – Spring Boot works as a self-contained application as it supplies its own server so need for a separate Tomcat server to deploy to!
  • “Mapped “{[/]}” onto public java.lang.String hello.SampleController.home()” – Spring (Application.java) has found the @RequestMapping annotation for the controller which we defined in the SampleController.java class so any requests to “/” should be handled appropriately without error (unless there’s a logic issue)
  • “Tomcat started on port(s): 8080 (http)” – great, now we know that the application is running locally on port 8080, so we should be able to check this easily in our browser by navigating to http://localhost:8080/
  • “Started Application in 2.495 seconds (JVM running for 2.887)” – Spring is happy that the application is running 🙂

Now if we navigate to http://localhost:8080/ we should see the following. Even though it doesn’t show the “/” on the end of “localhost:8080” the mapping for a slash on its own essentially means ‘home’ so this is normal. You can play around with mappings by changing the value in the @RequestMapping annotation e.g. change it to @RequestMapping(“/an_endpoint_woz_ere”) and you’ll need to navigate to http://localhost:8080/an_endpoint_woz_ere to see the “Hello World!” message instead.

blog8

That’s all for now

So although that was a simple app, you should now understand how to create a very basic standalone Spring Boot application, in addition to this you should also be able to work out how to add new endpoints (add more methods with “@RequestMapping()” annotations into the SampleController class) and also how to run your application. If you got stuck while following along with this post or would like to download my source code for it, I’ve uploaded it publicly on GitHub so please feel free to clone it down and play around with it.

From this point on it’s just a matter of playing around with the code, checking out new annotations and seeing what you can do with your new found love of Spring Boot! For a bit of inspiration, I’ve created a public repository of my own Spring Boot application that anyone is welcome to check out here on my GitHub repository. Based on what I learn from experimenting with Spring and Spring Boot in this hobby application I should be able to write some more blog posts in the future as my little project progresses.

As always, if you have any questions, suggestions or corrections please feel free to comment below, any and all feedback is gratefully received! 🙂

Thanks for reading,

Mark

Getting Started with Spring

Note: I’ve now (Sep 2017) added an extra step ‘3. b)’ to cover running Spring apps using IntelliJ Community Edition, so it is now possible to follow along without needing IntelliJ Ultimate Edition 🙂

In the last couple of weeks I’ve moved into a new team at work – the people are great, the office is amazing, life is wonderful. However, joining a new team means learning how they work and learning the technology they use, in this case I’m facing down the Spring Framework.

In the past I’ve worked with the Play! Framework to create and deploy a webapp, choosing it more or less entirely due to its simplicity and close knit relationship with plain old Java. This isn’t to say that Spring isn’t closely knit with Java, just that learning a billion annotations and figuring out how Java Beans worked seemed quite a daunting task at the time, as opposed to being able to to get straight into Java code in a fully-featured (perhaps a little bloated, in retrospect) framework. In essence, I was being lazy and doing my best to dodge having to learn a ton of new stuff before developing anything meaningful. Lesson learnt!

Anyways, karma has come right back around on me and here I am, now attempting to get up to speed with Spring as soon as my little brain can manage!

The purpose of this post is to share a brief ‘getting started’ guide. This isn’t here to explain all of the intricate steps in detail, this will come when I know these steps intimately myself, this guide is here to get anyone from a blank Maven project in IntelliJ to a very basic web application hosted on a local Tomcat server. Any code I’ve used is available on my GitHub repo for anyone to clone/download and play around with.

FYI – this guide is based on me using a Windows 10 PC, so some steps will be slightly different (read: ‘easier’, ‘less painful’ etc.) if using a Mac.

What is Spring?

As a one-liner – ‘Spring is a framework for developing applications or services that can be accessed/used through the web (via http)’. Basically, it lets you write applications (in Java) that can be deployed and then accessed by users through their web browser of choice (Chrome, Firefox, Safari etc.) by navigating to a URL e.g. http://marksamazingsite.com.

The main benefit of Spring is that it is designed to be modular. You start with the core functionality (Spring Boot) and from there you can choose to extend that by installing additional Spring modules. For instance, if you wanted to hook your application up to a database, you can use the Spring Data module, or if you want to account for security concerns you could apply the Spring Security module, or what if you wanted to develop your app towards Android users, there’s the Spring For Android module! There are loads of different modules to fit most needs, these are all described on the Spring projects website.

The inherent modularity of Spring means that you don’t need to start with a monolithic project and then strip away what you don’t need, it means that you can start with a simple, understandable base and build up gradually according to your needs. The obvious downside to this if you are a beginner (like me), is that implementing additional modules may require a bit of a learning curve, but I’ll find out as I use it more in future posts!

What is Tomcat and how do we use it with Spring?

Tomcat is a ‘web server’ technology, this means that installing and running it on a machine (be it your laptop, or a server in the cloud etc.) will enable you to ‘serve’ content or applications to other machines (clients) in your network, or over the internet if you host your Tomcat machine publicly. If you’re new to the idea of client-server architecture, have a look at this quick (~2 min) video to get an idea of how a server (machine with Tomcat installed, for example) can provide content, data or services to clients (other machines out there able to connect to the server) through the use of requests and responses.

Just to give a quick example of client-server interaction (request-response); by typing http://www.google.co.uk into your browser you are issuing a http request to the UK Google URL, Google will issue a response in the form of a webpage (HTML/CSS/JavaScript content) hosted from its server(s). If you typed in http://google.co.uk/somejunk instead, you’ll notice that it causes a 404 error, this is still a valid response from Google, all it’s saying is that it doesn’t understand your request (it can understand and provide content for google.co.uk, but does not have anything it can serve you for google.co.uk/somejunk aside from an error code). But what if you mistyped the url of Google? Say you typed in http://gogogogogogogg.co.uk instead, you’ll notice that nothing is served back to you, not even a custom error message like the 404 we saw a minute ago, from Google or anyone, because there isn’t (at the time of writing) a web server in the world that is setup to handle requests and provide responses for that URL. Simple!

In our case, we are going to install Tomcat on our PC and rather than sending requests to our Tomcat server externally, we can use a special ‘localhost’ URL which will allow us to write a Spring web application, host it (serve it from) our local Tomcat server installed on our machine, then access it using a URL of http://localhost:8080. This just means “send a http request to a local server on port 8080 (Tomcat’s default port)”.

What are we going to do?

  1. Create a new Maven project
  2. Download Apache Tomcat 8 to deploy our application to later on
  3. Set up a run configuration in IntelliJ to run our project on a local Tomcat server
  4. Write a basic SpringMVC (Spring 4) application
  5. Deploy and run your webapp!

Stuff you’ll need

IntelliJ Ultimate or Community Edition

If you haven’t already got hold of a free copy of IntelliJ Community Edition, I would highly recommend it. For general coding, in my opinion, it is THE BEST integrated development environment (IDE) for Java, Scala or pretty much anything else it supports!

In this guide we can use either the Ultimate Edition or the Community (free) Edition, if you’re a student you’ll likely be able to get the Ultimate edition for free using your institution’s details here. Step 3 (Setting up Run Configurations) has now been split into part a, and b, to set up a run configuration in either Ultimate or Community Editions’ respectfully. If you’re using Ultimate Edition you can use either of the two methods, however Community Edition will only allow you to use the latter of the two steps.

Apache Tomcat 8

It’s all good and well writing a Spring application, but we need some way of ‘hosting’ it from our machine so we that it can be accessed using a web browser (Chrome, Firefox, Safari etc.) to see it working as a live application! We’ll install and set it up for sue with IntelliJ after we run it manually to test it. We’ll set this up a step in the guide so that you can see the process of going from nothing at all on your machine, to deploying a Spring webapp to your very own local Tomcat server as a matter of easy steps.

Java 1.8

In this guide we’ll be using Tomcat 8 which relies on Java 7 or upwards being installed on your machine. I’d recommend using Java 8 straight away anyway though just to stay a little bit more up to date and allow you to take advantage of features such as Java Streams later on in development if you take your Spring project further.

Head to the Oracle website to download Java for your machine.

Let’s get to it!

A lot of the steps in this guide have been taken from a fantastic YouTube video by LynAs Sazzad, have a look at his video to get up and running quickly! As he moves quite fast through the steps in his video (a lot of pausing and going back was required!) and as he already had Tomcat set up to run his application, I’ve decided to write out some of the required steps but for the most part I’ll point you at his video to set up the code you need.

1. Create a new Maven project

Open IntelliJ and choose File -> New -> Project… then select the option for Maven from the list on the left hand side (it should be about halfway down).

Leave the Create from archetype option un-ticked and click next.

Give it a GroupId e.g. com.myTestProject. This option isn’t too important, it’s mainly important only for enterprise-level project where you’d need to define the domain or team your app will fall under such as com.marksCompany.financeWebApp.

ArtifactID is the name you want to assign to your app type in something like springMVCTest and click next. In the following screen the Project Name will likely autopopulate with the ArtifactID you gave your project so just check it is set and that you’re happy with the location of where your project will be stored and then click Finish.

2. Download Apache Tomcat 8 to deploy our application to later on

On my hunt to find a nice easy way of understanding how to install Tomcat on Windows 10, I found this awesome guide. It is a lengthy read but if you want to get to grips with webapps and understanding Tomcat, this covers everything you’ll likely need to know, conveniently enough it’s also got a nice section of downloading and running Tomcat. Below I’ve summarised the steps to downloading Tomcat and testing it by running it on your machine manually.

To download Tomcat for Windows, the easiest way I found was to download a zip file from Tomcat’s official website. At the time of writing, under the 8.5.14 heading there is a section called ‘Binary Distributions’ and in there is an option to download the ‘Core’.zip file (see red box below).

downlaodingtomcat.JPG

When it had finished downloading, I moved the downloaded .zip file into a new folder called H://Tomcat/Tomcat8/ on the hard drive of my computer and unzipped it there (right click .zip file -> Extract Here). This is just to give it a permanent home on my machine so any of my run configurations that I might put together later on have a definitive location in which to find and use Tomcat from.

As mentioned at the start. we need at least Java 1.7 (Java 7) installed on the machine running Tomcat 8 in order for it to work. Additionally we need to set up an environment variable called JAVA_HOME to point anything on our machine to its location. Hopefully, you’ve already downloaded Java through the Oracle website as explained at the beginning, if so follow the very last few instructions under the heading ‘to install the JDK Software and set JAVA_HOME on a Windows System’ on this site.

Now we are able to test that our downloaded version of Tomcat works, to do this click into the newly unzipped Tomcat file and go into the /bin directory. In here hold down shift and right click a blank are of the window to view the option to ‘Open command window here’, click this to enter command prompt. The only thing you need to do now is type ‘startup’ (without quotes) and press enter, this should open up another little command window, the whole thing should look similar to the output shown below.

Note: the equivalent command in Linux/Mac is ‘./catalinasa.sh run’

manualtomcatrun.JPG

Great, so in this new little window it’s telling you that Tomcat is running and that it’s listening on port 8080, so how do we access this? As we mentioned earlier on, we need to send it a request, as Tomcat is a web server, this therefore needs to be via http, so let’s open a web browser such as Chrome and navigate to http://localhost:8080. The result should look similar to the screenshot shown below.

tomcattest.JPG

This is Tomcat’s default page to serve to any requests, all this means is that we’ve not told Tomcat to serve anything other than this in response to any requests it receives, simple!

I don’t want to go too far into Tomcat stuff in this guide but I do want to quickly show you how to host your own content from this server manually before moving on. To do this I have created a very simple HTML file called index.html and stored this within a folder called marksApp in Tomcat’s webapps folder (see below).

simplehtmlfile.JPG

You should now be able to go to localhost:8080/marksApp (in my example) and take in the awesome beauty of my website.

marskapp.JPGNow that we’re happy that we have a working Tomcat installation, we just need to set up IntelliJ to use it and write the webapp to be served from it!

3. a) Set up a Tomcat run configuration in IntelliJ Ultimate Edition

In this step we’re simply telling IntelliJ how we would like it to run a program, in this case we’ll be writing a bunch of code that we’d like to run on a Tomcat server locally, so we’ll tell it just that by defining a ‘run configuration’ – a way of setting a particular way to run something.

To do this, from the top menu bar in IntelliJ choose Run -> Edit Configurations. In the

runconf1.png

Click the little green ‘+’ in the top left of the window that opens (see screenshot on the right).

You might get an option to choose Tomcat Server as shown in the image to the right, if not, click the option at the bottom titled ‘x items more (irrelevant)…’ and scroll down to find the Tomcat Server option. Once you’v found this click it to choose the Local or Remote options, we want to serve our app from a local Tomcat server so click ‘Local’ as shown below.runconf2.png

A new run configuration has now been created, you just needintellijtomcatlocalserversetup.JPG to edit it to your needs.

Firstly, set the Name field to something meaningful like SpringTomcat, now click the ‘Configure…’ button in the Application server section to bring up a small window (see screenshot to the right).

Clicking the ‘…’ therunconf2.png the right of the Tomcat Home box will allow you to tell IntelliJ where your Tomcat installation lives. Simply put, navigate to the unzipped version of Tomcat that you downloaded earlier, and click OK as shown on the left. You should now be presented with the original small window without the error icons and with some details of your Tomcat installation, click OK.

explodedstuff.PNG

The final thing we need to do is address the warning at the bottom of the run configuration, click the Fix button and choose the option suffixed with ‘exploded’ then click Apply and OK to finalise the run configuration.

3. b) Set up a Maven run configuration in IntelliJ Community Edition

In the more likely event that you’re following along using IntelliJ Community Edition, here is how you can easily set up a Maven run configuration to run your Spring applications. In this section I will be using the Tomcat7 plugin for Maven (rather than Tomcat8 as used previously in this guide). For the purposes of this guide the version of Tomcat being used isn’t important though.

Add the following plugin to your pom.xml.

Screen Shot 2017-09-16 at 16.23.24.png

From the Run menu, select ‘Edit Configurations…’

step1.png

The Run Configuration window will now pop up – click the grey ‘+’ icon in the top left of this window and choose the Maven option.

step2.png

Enter a name for your new run configuration and add ‘tomcat7:run’ in the Command Line box. Now click Apply and then OK to exit the window. This may require you to download and install Tomcat

step3.png

All you need to do now is choose your new run configuration from the Run menu!

step4.png

If your application fails to start, make sure that no other applications are running on the same port as the current application you’re trying to run. Most tutorials use the default port of 8080 so if this is the case, just stop any other apps you might be working on and try again. Other common issues relate to either the contents of your WEB-INF folder, or the dependencies in your pom.xml, so be sure to check them and Google any specific errors that come up.

4. Write a basic SpringMVC application

For this section I will point you directly at LynAs Sazzad‘s fantastic video for instructions on setting up all of the Spring code and dependencies in the pom.xml file. If you get stuck at any point or are having difficulty getting it working, my code is up on GitHub so feel free to use it for comparison or as a starting point for your own app!

The reason I’ve followed this tutorial specifically is that it uses Spring version 4, the latest release. Older versions of Spring use different annotations and also rely on .xml files for configuration of Beans etc. So this is all in aid of using the most up-to-date (at time of writing) version of Spring which uses Java instead of xml to work with Beans and in my opinion uses better structured annotations.

5. Deploy and run your webapp!

Once you have completed all of the above steps you can now use your run configuration to deploy your Spring webapp to your local Tomcat server and access it through the browser!runapp.PNG

At the top of the window in IntelliJ you’ll notice a Run Configuration dropdown with a green ‘play/run’ button next to it, make sure your new run configuration is selected and click the green run button.

The run console at the bottom of the screen will start churning out all sorts of messages, a lot of them will be in red text but are only ‘info’ messages rather than errors! When it’s finished deploying your app to the local Tomcat server it will show you the ‘deployed successfully’ message (see white lines of text in screenshot below) and will open up your application automatically in a web browser window, if it doesn’t just navigate to http://localhost:8080/ in your browser to view it.
runsuccess.PNG

runningapp.PNG

That’s all for now

That’s it! You’ve successfully set up a local Tomcat server, written a Spring application and deployed it to your server to be accessible by clients on your network (localhost)! In addition to this guide, I intend to write a sequel showing you how to deploy your application to a remote Tomcat server so it can be accessed by anyone on the internet. But for now that’s pretty good going 🙂

Also, as I start to learn more than just the absolute basics I’ll figure out what I can write about coherently and add that up on there as well!

If you have any questions or comments please as always feel free to message me or put them in the comments section below 🙂

Thanks for reading,

Mark.