How to deploy a Spring Boot Application into Tomcat

How to deploy a Spring Boot Application into Tomcat

Deploying applications is hard. In this tutorial you’ll see an easier way using Tomcat: you’ll create an authenticated web app and deploy it through the browser using the latest versions of Tomcat, Spring Boot, and Java.

Deploying applications is hard. In this tutorial you’ll see an easier way using Tomcat: you’ll create an authenticated web app and deploy it through the browser using the latest versions of Tomcat, Spring Boot, and Java.

Since version 9, Oracle has decreased the Java release cadence to six months so major version numbers are increasing at a much faster rate than before. The latest release is Java SE 11 (Standard Edition) which came out in September 2018. The biggest licensing change in this new release has led to one clear takeaway: to use the OpenJDK from now on. Open JDK is the free version of Java that you can now also get from Oracle. Also, Java 11 has long term support so this is the version you should be using for new projects going forward.

Start Your Java 11 App

Open up a console and run java -version to see what version of Java you are using.

[[email protected] demo]$ java -version
openjdk version "1.8.0_111"
OpenJDK Runtime Environment (build 1.8.0_111-b16)
OpenJDK 64-Bit Server VM (build 25.111-b16, mixed mode)
[[email protected] demo]$

Java 8 is shown as version 1.8.0.

SDKMAN is a great tool for keeping your development libraries up to date. To install it run

$ curl -s "" | bash

Note that SDKMAN only works on Linux and Unix-like systems. Windows users will need to install the latest Java manually.

If SDKMAN installs properly you will see instructions for getting the command to work in your current terminal.

All done!

Please open a new terminal, or run the following in the existing one:

	source "/home/karl/.sdkman/bin/"

Then issue the following command:

	sdk help

[[email protected] demo]$

Run the source command shown and the sdk command should be active.

Now install the latest Java simply with sdk install java.

[[email protected] demo]$ sdk install java

Downloading: java 11.0.2-open

In progress...

Once done java -version should show 11.0.2.

Done installing!

Setting java 11.0.2-open as default.
[[email protected] demo]$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
[[email protected] demo]$

NOTE: If you already have SDKMAN! and Java 11 installed, you can set it as the default using sdk default java 11.0.2-open.

Create a Spring Boot Project for Tomcat

The most popular way to start a Spring project is with Spring Initializr.

Navigate to in your favorite web browser, then choose your project options:

  • Leave as Maven, Java, and the latest stable Spring Boot (2.1.4)
  • Change the group and artifact if you wish
  • Click on More options and select Java 11
  • In the Dependencies box, type and choose Web, Security and Devtools. They should appear as Dependencies selected on the right

Now click Generate Project and a zip file will download with the project inside. Simply unzip and enter the directory from the command line. If you ls you’ll see five files and one directory (src).

[[email protected] demo]$ ls  mvnw  mvnw.cmd  pom.xml  src

mvnw is a script that allows you to use Maven without installing it globally. mvnw.cmd is the Windows version of this script. pom.xml describes your project, and src has your Java code inside. (Note there’s also a hidden .mvn directory where the embedded maven files sit!)

Let’s see what the project does. Type ./mvnw spring-boot:run and press enter. It may take a while for everything to install, but eventually, you should see something like this:

Tomcat started on port(s): 8080 (http) with context path ''
2019-03-17 19:56:49.342  INFO 10744 --- [  restartedMain] com.karl.demo.DemoApplication        	: Started DemoApplication in 3.022 seconds (JVM running for 3.56)

Note the message Tomcat started on port(s): 8080. Open a browser window to <a href="http://localhost:8080" target="_blank">http://localhost:8080</a> and you should see a login page.

You can authenticate using “user” for a username and the password that’s been printed to your terminal. After logging in, you’ll see a 404 error page because you haven’t created any code to show a landing page at /.

Add Secure Authentication to Your Spring Boot App

Let’s add authentication with Okta. Why Okta? Because you don’t want to worry about managing your users and hashing their passwords, do you? Friends don’t let friends write authentication - let the experts at Okta do it for you instead! After all, Okta’s API is built with Java and Spring Boot too!

Once you’ve signed up for a free account, go to Applications on your dashboard. Click Add Application, select Web, and click Next.

You should now be in the Application Settings page. Replace the Login Redirect URIs field with the following:


Click Done at the bottom. Copy your Client ID and Client secret from the Client Credentials section and keep them somewhere safe. Now right at the top click the API tab (next to Applications) and then Authorization Servers. Make note of the Issuer URI which looks like:


Create a file in your project at src/main/resources/application.yml and put those values inside:

    issuer: https://{yourOktaDomain}/oauth2/default  
    client-id: {clientId}
    client-secret: {clientSecret}

Now add the Okta Spring Boot Starter library as a dependency in your pom.xml.


Now edit your main Java entry file – which is probably somewhere like src/main/java/com/example/demo/ – and add the @RestController annotation to the class, as well as a homepage entry point:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

public class DemoApplication {

    public static void main(String[] args) {, args);

    public String currentUserName(Authentication authentication) {
    	DefaultOidcUser userDetails = (DefaultOidcUser) authentication.getPrincipal();
    	return "Hello, " + userDetails.getFullName();

Restart your app using ./mvnw spring-boot:run or use your IDE to run it.

Now when you visit <a href="http://localhost:8080" target="_blank">http://localhost:8080</a> you should see the Okta login screen.

Once you’ve entered in the details of an attached Okta user (you can use the same login as your Okta developer account here) you should see a welcome message with the full name you entered when you registered:

Hot Tip: Logging out of an OAuth2 session is more nuanced than one might first imagine. To keep testing the login process, I recommend you use private browsing windows to ensure the login screen returns; close them down when you are finished.

Stop your Spring Boot app so you can run Tomcat on its default port of 8080.

Set up Tomcat 9 for Your Spring Boot App

Getting Tomcat up and running couldn’t be easier. Start by downloading the binary compatible with your platform. Make sure to use the .zip or .tar.gz file and not the installer. Extract to a location and inside the bin directory run the startup script - for Linux/Mac and startup.bat for Windows.

[[email protected] bin]$ ./
Using CATALINA_BASE:   /home/karl/Downloads/apache-tomcat-9.0.19
Using CATALINA_HOME:   /home/karl/Downloads/apache-tomcat-9.0.19
Using CATALINA_TMPDIR: /home/karl/Downloads/apache-tomcat-9.0.19/temp
Using JRE_HOME:    	/home/karl/.sdkman/candidates/java/current
Using CLASSPATH:   	/home/karl/Downloads/apache-tomcat-9.0.19/bin/bootstrap.jar:/home/karl/Downloads/apache-tomcat-9.0.19/bin/tomcat-juli.jar
Tomcat started.
[[email protected] bin]$

Hot Tip: You can also use ./ run to start your app. This command will print the logs to your terminal so you don’t need to tail them to see what’s happening.

Browse to <a href="http://localhost:8080" target="_blank">http://localhost:8080</a> and you should see the Tomcat installation page.

Create a WAR File from Your Spring Boot Project

You now need to create a WAR file from your Spring Boot application. Add the following just after the <description> node in your pom.xml.


Remove the embedded Tomcat server by adding the following to your dependencies list:


Finally enable your application as a servlet by extending your main class with SpringBootServletInitializer:


public class DemoApplication extends SpringBootServletInitializer {

Now clean and package your application with the following command:

./mvnw clean package

You should see a message like the following:

[INFO] Building war: /home/karl/tst/demo/target/demo-0.0.1-SNAPSHOT.war

Take note where your new .war lives.

Deploy a WAR to Tomcat from the Browser

You may have noticed that on the right-hand side of the Tomcat welcome screen was three buttons: Server Status, Manager App, and Host Manager. You can deploy a WAR from Manager App but it needs authentication (and there are no users defined by default).

Add the following to conf/tomcat-users.xml in your Tomcat directory:

<user username="karl" password="secret" roles="manager-gui" />

You’ll need to restart Tomcat for this change to take effect. Because you started it directly you need to stop the process yourself. Find the process id using ps aux | grep tomcat.

[[email protected] bin]$ ps aux | grep tomcat
karl 	11813  180  1.9 7389172 159596 pts/0  Sl   09:44   0:07 /home/karl/.sdkman/candidates/java/current/bin/java -Djava.util.logging.config.file=/home/karl/Downloads/apache-tomcat-9.0.19/conf/ -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dignore.endorsed.dirs= -classpath /home/karl/Downloads/apache-tomcat-9.0.19/bin/bootstrap.jar:/home/karl/Downloads/apache-tomcat-9.0.19/bin/tomcat-juli.jar -Dcatalina.base=/home/karl/Downloads/apache-tomcat-9.0.19 -Dcatalina.home=/home/karl/Downloads/apache-tomcat-9.0.19 org.apache.catalina.startup.Bootstrap start
karl 	11881  0.0  0.0   6268  2280 pts/0	S+   09:44   0:00 grep tomcat
[[email protected] bin]$

Here my process ID is 11813. Use the kill command to kill it.

kill 11813

Restart the server by using as before. When you click on the Manager App button the user details you entered above should get you to the manager screen.

Scroll to the bottom to the WAR file to deploy section. Click Browse… and select the WAR file from before. Click Deploy.

If you scroll up you should see something like /demo-0.0.1-SNAPSHOT listed in the Applications section. Click on this will take us to <a href="http://localhost:8080/demo-0.0.1-SNAPSHOT" target="_blank">http://localhost:8080/demo-0.0.1-SNAPSHOT</a> which is where Tomcat is serving our application from. You’ll see a Bad Request error.

This is because the redirect URL is now wrong in our Okta app configuration - everything should be prepended with demo-0.0.1-SNAPSHOT. That name is a bit cumbersome. To change it rename your WAR file to demo.war (you can do this permanently by adding <finalName>demo</finalName> to the build section of your pom.xml). Now click Undeploy next to your app name in the manager window, and redeploy the WAR. Now the app should be under /demo.

Now in your Okta application config prepend all the URLs with /demo, e.g. <a href="http://localhost:8080/demo/login/oauth2/code/okta" target="_blank">http://localhost:8080/demo/login/oauth2/code/okta</a> (you do this by clicking Edit and then Save). Now clicking on your /demo app in the manager (or browsing to <a href="http://localhost:8080/demo" target="_blank">http://localhost:8080/demo</a>) should show you the welcome screen as before.

Hot Tip: To ensure your local development setup matches the machine you are deploying to, make sure the embedded Tomcat version is the same as your external server by adding the following to your pom.xml:


Spring Boot Tutorial For Beginner- Spring Boot Full Course

Spring Boot Tutorial For Beginner- Spring Boot Full Course

This "Spring Boot Tutorial For Beginner- Spring Boot Full Course" video will help you learn Spring Boot Framework from scratch with examples. This Spring Tutorial is ideal for both beginners as well as professionals who want to master the Spring Boot Framework

Spring Boot Full Course - Learn Spring Boot In 4 Hours | Spring Boot Tutorial For Beginner

Below are the topics covered in this Spring Boot Tutorial for Beginners video:

1:40 What is Spring Boot?
2:35 Features of Spring Boot
3:50 Why Do We Need Spring Boot?
4:30 Spring Boot Market Trend
5:15 Spring vs Spring Boot
6:25 Install & Setup Spring Boot
6:45 System Requirements
7:35 Install & Set up Spring Boot CLI
14:00 Install & Setup Spring Tool Suite
25:40 Model View Controller
26:00 What is MVC?
27:35 Model View Controller Workflow
29:00 What is Dependency Injection?
31:50 Inversion of Control
33:10 Types of Dependency Injection
34:05 Benefits of Dependency Injection
48:35 Auto wire
49:50 Create First Web Application Using Spring Boot
1:06:50 Create a Web Application To Pass Client Data
1:13:40 Model View & Object Example
1:20:30 Create a Submission Form In Spring Boot
1:40:50 Connect Web Application To Database
2:04:50 REST API
2:07:35 What is REST API?
2:08:50 Features of REST API
2:09:35 Principles of REST API
2:11:40 Methods of REST API
2:12:20 REST API Hands-On
2:35:55 Spring Data REST
2:36:55 Spring Data REST Hands-On
2:46:35 Spring Security
2:47:30 Secure Applications Using Spring Boot
2:58:56 Spring Boot Interview Questions

Full-stack Reactive Java with Spring Framework, Spring Boot and Project Reactor

Full-stack Reactive Java with Spring Framework, Spring Boot and Project Reactor

Reactive programming offers Java developers a way to build message-driven, elastic, resilient, and responsive services...yet many Java developers don't know where to begin.

Reactive programming offers Java developers a way to build message-driven, elastic, resilient, and responsive services...yet many Java developers don't know where to begin.

The Reactive Streams initiative provides a baseline and Project Reactor provides a great way to become immediately productive, leveraging reactive capabilities from end to end. Whether you're coming from a Spring MVC environment or a functional perspective, Reactor empowers you to spin up fully reactive Spring Boot 2 applications quickly and efficiently.

In this talk, the presenter dives into the net-new Netty-based web runtime and shows you how to:

  • integrate easily with existing Spring-stack technologies
  • easily transition from blocking to reactive applications & systems
  • define your API in an imperative style and functionally, reaping all benefits both ways
  • leverage powerful new testing mechanisms to make code better and life easier

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Java Spring Framework and Spring Boot

Java Programming Masterclass for Software Developers

100+ Java Interview Questions and Answers In 2019

Build a microservices architecture with Spring Boot and Spring Cloud

Spring Framework - Top 50 Questions for Interview In 2019

Building a Simple CRUD App using Spring Boot, MySQL, JPA/Hibernate

Full Stack Web Development with Angular and Spring MVC

Spring Boot vs. Spring MVC vs. Spring: How Do They Compare?

Spring Boot vs. Spring MVC vs. Spring: How Do They Compare?

In this article, you will receive overviews of Spring, Spring MVC, and Spring Boot, learn what problems they solve, and where they’re best applied. The most important thing that you will learn is that Spring, Spring MVC, and Spring Boot are not competing for the same space. They solve different problems and they solve them very well.

In this article, you will receive overviews of Spring, Spring MVC, and Spring Boot, learn what problems they solve, and where they’re best applied. The most important thing that you will learn is that Spring, Spring MVC, and Spring Boot are not competing for the same space. They solve different problems and they solve them very well.

Spring, Spring Boot, Spring MVC, there are springs everywhere! Let's walk through where and when you should apply each of these tools.

What Is the Core Problem That Spring Framework Solves?

Think long and hard. What’s the problem Spring Framework solves?

The most important feature of Spring Framework is Dependency Injection. At the core of all Spring Modules is Dependency Injection or IOC Inversion of Control.
Why is this important? Because, when DI or IOC is used properly, we can develop loosely coupled applications. And loosely coupled applications can be easily unit tested.

Let’s consider a simple example.

Example Without Dependency Injection

Consider the example below: WelcomeController depends on WelcomeService to get the welcome message. What is it doing to get an instance of WelcomeService?

WelcomeService service = new WelcomeService();

It’s creating an instance of it. And that means they are tightly coupled. For example: If I create a mock for WelcomeService in a unit test for WelcomeController, how do I make WelcomeController use the mock? Not easy!

public class WelcomeController {

    private WelcomeService service = new WelcomeService();

    public String welcome() {
        return service.retrieveWelcomeMessage();

Same Example with Dependency Injection

The world looks much simpler with dependency injection. You let the Spring Framework do the hard work. We just use two simple annotations: @Component and @Autowired.

  • Using @Component, we tell Spring Framework: Hey there, this is a bean that you need to manage.
  • Using @Autowired, we tell Spring Framework: Hey find the correct match for this specific type and autowire it in.

In the example below, Spring framework would create a bean for WelcomeService and autowire it into WelcomeController.

In a unit test, I can ask the Spring framework to auto-wire the mock of WelcomeService into WelcomeController. (Spring Boot makes things easy to do this with @MockBean. But, that’s a different story altogether!)

public class WelcomeService {
    //Bla Bla Bla

public class WelcomeController {

    private WelcomeService service;

    public String welcome() {
        return service.retrieveWelcomeMessage();

What Else Does Spring Framework Solve?

Problem 1: Duplication/Plumbing Code

Does Spring Framework stop with Dependency Injection? No. It builds on the core concept of Dependency Injection with a number of Spring Modules

  • Spring JDBC
  • Spring MVC
  • Spring AOP
  • Spring ORM
  • Spring JMS
  • Spring Test

Consider Spring JMS and Spring JDBC for a moment.

Do these modules bring in any new functionality? No. We can do all this with J2EE or Java EE. So, what do these bring in? They bring in simple abstractions. The aim of these abstractions is to

  • Reduce Boilerplate Code/Reduce Duplication
  • Promote Decoupling/Increase Unit Testability

For example, you need much less code to use a JDBCTemplate or a JMSTemplate compared to a traditional JDBC or JMS.

Problem 2: Good Integration With Other Frameworks

The great thing about Spring Framework is that it does not try to solve problems that are already solved. All that it does is to provide a great integration with frameworks which provide great solutions.

  • Hibernate for ORM
  • iBatis for Object Mapping
  • JUnit and Mockito for Unit Testing
What Is the Core Problem That Spring MVC Framework Solves?

Spring MVC Framework provides decoupled way of developing web applications. With simple concepts like Dispatcher Servlet, ModelAndView and View Resolver, it makes it easy to develop web applications.## Why Do We Need Spring Boot?

Spring based applications have a lot of configuration.

When we use Spring MVC, we need to configure component scan, dispatcher servlet, a view resolver, web jars(for delivering static content) among other things.

        <property name="prefix">
        <property name="suffix">

  <mvc:resources mapping="/webjars/**" location="/webjars/"/>

The code snippet below shows the typical configuration of a dispatcher servlet in a web application.



When we use Hibernate/JPA, we would need to configure a datasource, an entity manager factory, a transaction manager among a host of other things.

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        <property name="driverClass" value="${db.driver}" />
        <property name="jdbcUrl" value="${db.url}" />
        <property name="user" value="${db.username}" />
        <property name="password" value="${db.password}" />

    <jdbc:initialize-database data-source="dataSource">
        <jdbc:script location="classpath:config/schema.sql" />
        <jdbc:script location="classpath:config/data.sql" />

        <property name="persistenceUnitName" value="hsql_pu" />
        <property name="dataSource" ref="dataSource" />

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

Problem #1: Spring Boot Auto Configuration: Can We Think Different?

Spring Boot brings a new thought process around this.

Can we bring more intelligence into this? When a spring mvc jar is added into an application, can we auto configure some beans automatically?* How about auto-configuring a Data Source if Hibernate jar is on the classpath?

  • How about auto-configuring a Dispatcher Servlet if Spring MVC jar is on the classpath?

There would be provisions to override the default auto configuration.

Spring Boot looks at a) Frameworks available on the CLASSPATH b) Existing configuration for the application. Based on these, Spring Boot provides basic configuration needed to configure the application with these frameworks. This is called Auto Configuration.### Problem #2: Spring Boot Starter Projects: Built Around Well-Known Patterns

Let’s say we want to develop a web application.

First of all, we would need to identify the frameworks we want to use, which versions of frameworks to use and how to connect them together.

All web application have similar needs. Listed below are some of the dependencies we use in our Spring MVC Course. These include Spring MVC, Jackson Databind (for data binding), Hibernate-Validator (for server side validation using Java Validation API) and Log4j (for logging). When creating this course, we had to choose the compatible versions of all these frameworks.





Here’s what the Spring Boot documentations says about starters.

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.
Let’s consider an example starter: Spring Boot Starter Web.

If you want to develop a web application or an application to expose restful services, Spring Boot Start Web is the starter to pick. Let’s create a quick project with Spring Boot Starter Web using Spring Initializr.

Dependency for Spring Boot Starter Web


The following screenshot shows the different dependencies that are added into our application

Dependencies can be classified into:

  • Spring: core, beans, context, aop
  • Web MVC: (Spring MVC)
  • Jackson: for JSON Binding
  • Validation: Hibernate Validator, Validation API
  • Embedded Servlet Container: Tomcat
  • Logging: logback, slf4j

Any typical web application would use all these dependencies. Spring Boot Starter Web comes pre-packaged with these. As a developer, I would not need to worry about either these dependencies or their compatible versions.

Spring Boot Starter Project Options

As we see from Spring Boot Starter Web, starter projects help us in quickly getting started with developing specific types of applications.

  • spring-boot-starter-web-services: SOAP Web Services
  • spring-boot-starter-web: Web and RESTful applications
  • spring-boot-starter-test: Unit testing and Integration Testing
  • spring-boot-starter-jdbc: Traditional JDBC
  • spring-boot-starter-hateoas: Add HATEOAS features to your services
  • spring-boot-starter-security: Authentication and Authorization using Spring Security
  • spring-boot-starter-data-jpa: Spring Data JPA with Hibernate
  • spring-boot-starter-cache: Enabling Spring Framework’s caching support
  • spring-boot-starter-data-rest: Expose Simple REST Services using Spring Data REST
Other Goals of Spring Boot

There are a few starters for technical stuff as well

  • spring-boot-starter-actuator: To use advanced features like monitoring and tracing to your application out of the box
  • spring-boot-starter-undertow, spring-boot-starter-jetty, spring-boot-starter-tomcat: To pick your specific choice of Embedded Servlet Container
  • spring-boot-starter-logging: For Logging using logback
  • spring-boot-starter-log4j2: Logging using Log4j2

Spring Boot aims to enable production ready applications in quick time.

  • Actuator: Enables Advanced Monitoring and Tracing of applications.
  • Embedded Server Integrations: Since the server is integrated into the application, I would need to have a separate application server installed on the server.
  • Default Error Handling