Разверните загрузочное приложение Spring в Tomcat
«Я люблю писать код аутентификации и авторизации». Нет Java-разработчика. Надоело строить одни и те же экраны входа снова и снова? Попробуйте API Okta для размещенной аутентификации, авторизации и многофакторной аутентификации.
Развертывание приложений сложно. Часто вам нужен консольный доступ к серверу, с которого вы извлекаете последний код и затем вручную создаете экземпляр в своем контейнере. В этом руководстве вы увидите более простой способ использования Tomcat: вы создадите аутентифицированное веб-приложение и развернете его через браузер, используя последние версии Tomcat, Spring Boot и Java.
Начиная с версии 9, Oracle сократила частоту выпусков Java до шести месяцев, поэтому номера основных версий растут гораздо быстрее, чем раньше. Последним выпуском является Java SE 11 (Standard Edition), вышедшая в сентябре 2018 года. Самое большое изменение лицензий в этом новом выпуске привело к однозначному выводу: использовать OpenJDK с этого момента. Open JDK – это бесплатная версия Java, которую вы также можете получить от Oracle. Кроме того, Java 11 имеет долгосрочную поддержку, поэтому эту версию вы должны использовать для новых проектов в будущем.
Запустите приложение Java 11
Откройте консоль и запустите java -version чтобы увидеть, какую версию Java вы используете.
Java 8 показана как версия 1.8.0 .
SDKMAN – отличный инструмент для поддержания ваших библиотек разработки в актуальном состоянии. Чтобы установить его, запустите
Обратите внимание, что SDKMAN работает только в Linux и Unix-подобных системах. Пользователи Windows должны будут установить последнюю версию Java вручную .
Если SDKMAN установлен правильно, вы увидите инструкции по получению команды для работы в вашем текущем терминале.
Запустите указанную source команду, и команда sdk должна быть активной.
Теперь установите последнюю sdk install java Java просто с sdk install java .
После того, как java -version 11.0.2 должно 11.0.2 .
ПРИМЕЧАНИЕ: если у вас уже есть SDKMAN! и Java 11 установлена, вы можете установить ее по умолчанию, используя sdk default java 11.0.2-open .
Создайте проект Spring Boot для Tomcat
Самый популярный способ начать проект Spring с Spring Initializr

Перейдите к файлу start.spring.io в своем любимом веб-браузере, затем выберите параметры проекта:
- Оставьте как Maven, Java и последнюю стабильную версию Spring Boot (2.1.4)
- Измените группу и артефакт, если хотите
- Нажмите на Дополнительные параметры и выберите Java 11
- В поле Зависимости введите и выберите Web , Security и Devtools . Они должны отображаться как зависимости, выбранные справа
Теперь нажмите Generate Project, и zip-файл будет загружен вместе с проектом внутри. Просто разархивируйте и введите каталог из командной строки. Если вы увидите ls вы увидите пять файлов и один каталог ( src ).
mvnw – это скрипт, который позволяет вам использовать Maven, не устанавливая его глобально. mvnw.cmd – версия этого скрипта для Windows. pom.xml описывает ваш проект, а src содержит ваш Java-код внутри. (Обратите внимание, что есть также скрытый каталог .mvn котором .mvn встроенные файлы maven!)
Давайте посмотрим, что делает проект. Введите ./mvnw spring-boot:run и нажмите ввод. Все может занять некоторое время для установки, но в конечном итоге вы должны увидеть что-то вроде этого:
Обратите внимание на сообщение Tomcat started on port(s): 8080 . Откройте окно браузера по http://localhost:8080 и вы должны увидеть страницу входа.

Вы можете аутентифицироваться, используя «user» для имени пользователя и пароля, который был напечатан на вашем терминале. После входа в систему вы увидите страницу с ошибкой 404, потому что вы не создали никакого кода для отображения целевой страницы в / .
Добавьте безопасную аутентификацию в приложение Spring Boot
Давайте добавим аутентификацию с Okta. Почему окта? Потому что вы не хотите беспокоиться об управлении своими пользователями и хэшировании их паролей, не так ли? Друзья не позволяют друзьям писать аутентификацию – пусть эксперты сделают это за вас! В конце концов, API Okta также построен на Java и Spring Boot!
После того, как вы зарегистрировали бесплатную учетную запись, перейдите в раздел Приложения на панели инструментов. Нажмите « Добавить приложение» , выберите « Интернет» и нажмите « Далее» .
Теперь вы должны быть на странице настроек приложения. Замените поле URI для перенаправления входа следующим:
Нажмите Готово внизу. Скопируйте свой идентификатор клиента и секрет клиента из раздела «Учетные данные клиента» и храните их в безопасном месте. Теперь прямо вверху щелкните вкладку API (рядом с Приложениями ) и затем Серверы авторизации . Запишите URI эмитента, который выглядит следующим образом:
Создайте файл в своем проекте в src/main/resources/application.yml и поместите эти значения внутрь:
Теперь добавьте библиотеку Okta Spring Boot Starter в качестве зависимости в вашем pom.xml .
Теперь отредактируйте ваш основной файл ввода Java – который, вероятно, находится где-то вроде src/main/java/com/example/demo/DemoApplication.java – и добавьте аннотацию @RestController к классу, а также точку входа на домашней странице:
Перезапустите приложение, используя ./mvnw spring-boot:run или используйте свою IDE для его запуска.
Теперь, когда вы посещаете http://localhost:8080 вы должны увидеть экран входа Okta.

Как только вы введете данные подключенного пользователя Okta (вы можете использовать тот же логин, что и ваша учетная запись разработчика Okta здесь), вы должны увидеть приветственное сообщение с полным именем, которое вы ввели при регистрации:

Подсказка: выход из сеанса OAuth2 более нюансов, чем можно себе представить. Чтобы продолжить тестирование процесса входа в систему, я рекомендую использовать закрытые окна просмотра, чтобы обеспечить возврат экрана входа в систему; закройте их, когда вы закончите.
Остановите приложение Spring Boot, чтобы вы могли запустить Tomcat на порте по умолчанию 8080.
Настройте Tomcat 9 для приложения Spring Boot
Запуск Tomcat и запуск не может быть проще. Начните с загрузки двоичного файла, совместимого с вашей платформой. Убедитесь, что вы используете файл .zip или .tar.gz а не установщик. Извлеките его в папку и в каталоге bin запустите сценарий запуска – startup.sh для Linux / Mac и startup.bat для Windows.
Подсказка: вы также можете использовать ./catalina.sh run для запуска вашего приложения. Эта команда напечатает логи на ваш терминал, поэтому вам не нужно следить за ними, чтобы увидеть, что происходит.
Перейдите по http://localhost:8080 и вы должны увидеть страницу установки Tomcat.

Создайте WAR-файл из вашего проекта Spring Boot
Теперь вам нужно создать WAR-файл из вашего приложения Spring Boot. Добавьте следующее сразу после узла <description> в вашем pom.xml .
Удалите встроенный сервер Tomcat, добавив в список зависимостей следующее:
Наконец, включите ваше приложение в качестве сервлета, расширив основной класс с помощью SpringBootServletInitializer :
Теперь очистите и упакуйте свое приложение с помощью следующей команды:
Вы должны увидеть сообщение, подобное следующему:
Обратите внимание, где живет ваш новый .war .
Разверните WAR для Tomcat из браузера
Возможно, вы заметили, что с правой стороны экрана приветствия Tomcat было три кнопки: Состояние сервера , Приложение менеджера и Диспетчер хостов . Вы можете развернуть WAR-файл из приложения Manager, но для этого требуется аутентификация (и по умолчанию пользователи не определены).
Добавьте следующее в файл conf/tomcat-users.xml в каталоге Tomcat:
Вам нужно будет перезапустить Tomcat, чтобы изменения вступили в силу. Поскольку вы начали это напрямую, вам нужно остановить процесс самостоятельно. Найдите идентификатор процесса с помощью ps aux | grep tomcat ps aux | grep tomcat .
Здесь мой идентификатор процесса – 11813. Используйте команду kill, чтобы убить его.
Перезагрузите сервер, используя startup.sh как и раньше. Когда вы нажимаете кнопку « Приложение менеджера», введенные выше данные пользователя должны открыть экран менеджера.

Прокрутите вниз до WAR-файла, чтобы развернуть раздел. Нажмите Обзор … и выберите файл WAR из ранее. Нажмите Развернуть .
Если вы прокрутите вверх, вы увидите что-то вроде /demo-0.0.1-SNAPSHOT указанное в разделе « Приложения ». Нажмите здесь, чтобы перейти на http://localhost:8080/demo-0.0.1-SNAPSHOT откуда Tomcat обслуживает наше приложение. Вы увидите ошибку Bad Request.

Это связано с тем, что URL-адрес перенаправления теперь неверен в нашей конфигурации приложения Okta – все должно начинаться с demo-0.0.1-SNAPSHOT . Это имя немного громоздко. Чтобы изменить его, переименуйте ваш WAR-файл в demo.war (вы можете сделать это навсегда, добавив <finalName>demo</finalName> в раздел сборки вашего pom.xml ). Теперь нажмите Undeploy рядом с именем вашего приложения в окне менеджера и повторно разверните WAR. Теперь приложение должно быть в /demo .
Теперь в настройках приложения Okta добавьте все URL-адреса с помощью /demo , например, http://localhost:8080/demo/login/oauth2/code/okta (вы делаете это, нажимая Edit, а затем Save ). Теперь, нажав на ваше /demo приложение в менеджере (или перейдя по http://localhost:8080/demo ), вы увидите экран приветствия, как и раньше.
Совет: чтобы убедиться, что ваши локальные настройки разработки соответствуют машине, на которой вы развертываете, убедитесь, что встроенная версия Tomcat совпадает с вашим внешним сервером, добавив следующее в ваш pom.xml :
Узнайте больше о Tomcat, Spring Boot и Java 11
Отлично, вы удаленно развернули приложение Spring Boot 2.1 в Tomcat 9, все с поддержкой Java 11!
Надеюсь, вы нашли этот урок полезным. Вы можете найти репозиторий GitHub для этого примера в oktadeveloper / okta-spring-boot-tomcat-example .
Проверьте некоторые из этих ссылок ниже для получения дополнительной информации:
- i18n в Java 11, Spring Boot и JavaScript
- Spring Boot 2.1: выдающаяся поддержка OIDC, OAuth 2.0 и Reactive API
- Перенесите приложение Spring Boot на новейшую и лучшую Spring Security и OAuth 2.0
- Создавайте реактивные API с помощью Spring WebFlux
- Создайте реактивное приложение с помощью Spring Boot и MongoDB
- Baeldung Как развернуть файл WAR в Tomcat
Как то, что вы узнали сегодня? Подпишитесь на нас в Twitter и подпишитесь на наш канал на YouTube .
«Развертывание приложения Spring Boot в Tomcat» первоначально было опубликовано в блоге разработчиков Okta 16 апреля 2019 года.
«Я люблю писать код аутентификации и авторизации». Нет Java-разработчика. Надоело строить одни и те же экраны входа снова и снова? Попробуйте API Okta для размещенной аутентификации, авторизации и многофакторной аутентификации.
Deploy a Spring Boot Application into Tomcat
Deploying applications is hard. Often you need console access to the server from which you pull the latest code and then manually instantiate into your container. 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.
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
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.
Run the source command shown and the sdk command should be active.
Now install the latest Java simply with sdk install java .
Once done java -version should show 11.0.2 .
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 start.spring.io in your favorite web browser, then choose your project options:
- Leave as Maven, Java, and the latest stable Spring Boot (2.4.4)
- Change the group and artifact if you wish
- 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 ).
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:
Note the message Tomcat started on port(s): 8080 . Open a browser window to http://localhost:8080 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!
Before you begin, you’ll need a free Okta developer account. Install the Okta CLI and run okta register to sign up for a new account. If you already have an account, run okta login . Then, run okta apps create . Select the default app name, or change it as you see fit. Choose Web and press Enter.
Select Okta Spring Boot Starter. Accept the default Redirect URI values provided for you. That is, a Login Redirect of http://localhost:8080/login/oauth2/code/okta and a Logout Redirect of http://localhost:8080 .
What does the Okta CLI do?
The Okta CLI will create an OIDC Web App in your Okta Org. It will add the redirect URIs you specified and grant access to the Everyone group. You will see output like the following when it’s finished:
Open src/main/resources/application.properties to see the issuer and credentials for your app.
NOTE: You can also use the Okta Admin Console to create your app. See Create a Spring Boot App for more information.
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/DemoApplication.java – and add the @RestController annotation to the class, as well as a homepage entry point:
Restart your app using ./mvnw spring-boot:run or use your IDE to run it.
Now when you visit http://localhost:8080 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 — startup.sh for Linux/Mac and startup.bat for Windows.
Hot Tip: You can also use ./catalina.sh 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 http://localhost:8080 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 :
Now package your application with the following command:
You should see a message like the following:
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:
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 .
Here my process ID is 11813 . Use the kill command to kill it.
Restart the server by using startup.sh 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 http://localhost:8080/demo-0.0.1-SNAPSHOT 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 .
Run okta login and open the resulting URL in your browser. Log in and go to the Applications section. Edit your application’s general settings and prepend all the URLs with /demo , e.g. http://localhost:8080/demo/login/oauth2/code/okta . Now clicking on your /demo app in the manager (or browsing to http://localhost:8080/demo ) 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 :
Learn More About Tomcat, Spring Boot, and Java 11
Well done — you’ve remotely deployed a Spring Boot 2.4 application to Tomcat 9, all backed by Java 11!
I hope you found this tutorial useful. You can find the GitHub repo for this example at oktadeveloper/okta-spring-boot-tomcat-example.
Check out some of these links below for more information:
Like what you learned today? Follow us on Twitter and subscribe to our YouTube channel.
Changelog:
- Apr 3, 2021: Updated to Spring Boot 2.4 and Okta CLI for setup. See this post’s changes in okta-blog#688; the example app’s changes can be found in okta-spring-boot-tomcat-example#2.
Okta Developer Blog Comment Policy
We welcome relevant and respectful comments. Off-topic comments may be removed.
How to deploy spring boot web application on tomcat server
I have created spring boot web application, but I am unable to deploy spring boot web application WAR file on tomcat and I am able to run it as java application. How to run spring boot application as web service on tomcat. I am using following code. If it is possible to run on tomcat plz help me using annotations without using web.xml and with using web.xml.
Following code for rest controller
Following Pom.xml I am using
![]()
5 Answers 5
Here are two good documentations on how to deploy the Spring Boot App as a war file.
You can follow this spring boot howto-traditional-deployment documentation —
Steps according to this documentation —
You update your application’s main class to extend SpringBootServletInitializer .
The next step is to update your build configuration so that your project produces a war file rather than a jar file. <packaging>war</packaging>
Mark the embedded servlet container dependency as provided.
and one more way —
See this spring io documentation which outlines how to deploy the spring boot app to an application server.
Change jar packaging to war .
Comment out the declaration of the spring-boot-maven-plugin plugin in your pom.xml
Add a web entry point into your application by extending SpringBootServletInitializer and override the configure method
Remove the spring-boot-starter-tomcat dependency and modfiy your spring-boot-starter-web dependency to
In your pom.xml , remove spring-beans and spring-webmvc dependencies. The spring-boot-starter-web dependency will include those dependecies.
Spring boot provides option to deploy the application as a traditional war file in servlet 3.x (without web.xml)supporting tomcat server.Please see spring boot documentation for this. I will brief what you need to do here.
step 1 : modify pom.xml to change the packaging to war:(that you already did)
step 2 : change your dependency
step 3 :modify your war name (if you need to avoid the version details appended with the war name) in pom.xml under <build> tag.
step 4 : run maven build to create war : clean install step 5 : deploy the generated war file web-service.war in tomcat and request url in browser http://<tomcat ip>:<tomcat port>/web-service/hello
You should get Hello World .
Note: Also you can remove redundant dependencies as @Ali Dehghani said.
![]()
Mark the spring-boot-starter-tomcat dependency as provided , like:
Note1: Remove redundant dependencies from your pom.xml like:
They are part of spring boot starter packages
Note2: Make jar not war
![]()
The process of converting a spring boot jar to a spring boot war is documented at: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging Long story short, set your starter class the way you did in your example and then switch the packaging from jar to war in the .pom file. Furthermore, you need to set the spring-boot-starter-tomcat dependency to provided. Once again, the process is documented in it’s complete form at the link above. Further information about this subject is available in the spring io guide, «Converting a Spring Boot JAR Application to a WAR» which is available at https://spring.io/guides/gs/convert-jar-to-war/ If i can be of any further assistance, let me know and i will help you.
I was faced with this problem. Much of the above is good advice. My problem was to deploy on the Pivotal TC server initially.
Make the packaging in the pom a WAR.
Add dependencies to the pom
I used an Application class to hold the main(). Main had configuration code so that EntityManager etc could be injected. This EntityManager used information from the ApplicationContext and persistence.xml files for persistence information. Worked fine under SpringBoot but not under Tomcat. In fact under Tomcat the Main() is not called. The Application class extends SpringBootServletInitializer .
The following method is added to the Application class:
Only the last line is required — the other code was held in main() before and was moved here to get injection of the EntityManager working.