Как запустить спринг приложение из под сервера tomcat
Перейти к содержимому

Как запустить спринг приложение из под сервера tomcat

  • автор:

How to Deploy Spring-Boot Application on Tomcat server

This tutorial will demonstrate how to deploy a spring boot application on tomcat server.

Requirements

  • Spring Boot 2.2.6
  • Apache Tomcat 9.0
  • Java 8
  • IntelliJ IDEA

Apache Tomcat is an open-source implementation of the Java Servlet, JavaServer Pages, Java Expression Language and WebSocket technologies. Tomcat provides a “pure Java” HTTP web server environment in which Java code can run.
-Wikipedia

Let’s get started

As the first step, we have to create a spring boot project. Spring Initializer page which is one of the easiest ways to create spring boot project scratch.

  1. Visit https://start.spring.ioweb page
  2. Please Select bellow mentioned things
    Project: Maven Project
    Language: Java
    Spring Boot:2.2.6
    Enter the metadata your own
    Packaging: war
    Java:8 (in my case)
  3. As the dependencies add followings
    Spring Web
  4. after click generate. It will be downloaded project to your computer.

Then We’ll download Apache tomcat server

  1. To download tomcat, refer this link https://tomcat.apache.org/
  2. Select the Tomcat version on the left side menu. In my case, I’m going to use version 9. Fell free to use any version but above version 8 is recommended.
  3. Download Core zip in the binary distributions.
    (Extract zip that already downloaded)

Now we’ll try to run the created project on tomcat. For that, I use IntelliJ IDEA. (There are more ways to do this step)

  1. Import project that you’ve already created after extract.

2. Let’s see how to add tomcat server to IntelliJ. First, you need to add Tomcat and TomEE Integration(If you’ve already installed this plugin, please skip this step)
Preference > Plugins > Search (Tomcat and TomEE Integration) and select > Click Install JetBrains plugins button at the bottom > Install > Restart IntelliJ

3. Preference > Buil, Execution, Deployment > Application Server > Click + Icon > Select Tomcat EE Server > Give location’s path that you’ve downloaded tomcat binary in previous step.

4. Before going to the next step, you need to make sure tomcat starter dependency is an exit in the pom.xml and packaging type is war

5. Now, We’ll configure run time configuration. For that click the drop-down arrow on the top right corner of the tool menu. After clicking the arrow, edit configuration pop up will appear. Then click on that. Now you can see Run/Debug Configurations window box.
Then click + icon at the top left corner on the pop-up window.
Scroll down and select Tomcat Server > Local

6. In the server configuration window, you can give a name that you like for the server. In the server, tab selects JRE version. All other settings left as default.
Select the Deployment tab and click + icon in “deploy at server startup” > Select “Artifact” > Select name of your project: war (In my case example-tomcat: war) > Give name which you like for application context ( by this name you can access your application in tomcat server)

Разверните загрузочное приложение 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

Приложение Spring Boot

Перейдите к файлу 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.

Приложение Spring Boot

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

Приложение Spring Boot

Подсказка: выход из сеанса 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.

Приложение Spring Boot

Создайте 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 как и раньше. Когда вы нажимаете кнопку « Приложение менеджера», введенные выше данные пользователя должны открыть экран менеджера.

Приложение Spring Boot

Прокрутите вниз до WAR-файла, чтобы развернуть раздел. Нажмите Обзор … и выберите файл WAR из ранее. Нажмите Развернуть .

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

Приложение Spring Boot

Это связано с тем, что 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 для размещенной аутентификации, авторизации и многофакторной аутентификации.

How to Deploy Spring Boot Applications to Tomcat Application Server

We sometimes encounter a variety of application servers to deploy in our projects due to the different customers we work with. Although Spring Boot has a built-in Embedded Tomcat server, this is mainly used for development or microservice deployment. If you end up deploying your application to a client’s Tomcat / JBoss EAP / IBM WebSphere environment, you still need to make some adjustments. Today’s article is an in-depth look at the setup process and complete knowledge of deploying to Apache Tomcat®.

spring boot & apache tomcat

Create sample applications

Quickly building a project using the Spring Boot CLI

Open the project using Visual Studio Code.

Add a HomeController controller

File path: src/main/java/com/duotify/app1/controllers/HomeController.java .

Addendum: You can add a <defaultGoal>spring-boot:run</defaultGoal> setting under the <build> node in pom.xml , then you can just type mvn and Spring Boot will start running automatically! ��

Adjust the project

To deploy to a standalone Tomcat server, the following adjustments must be made in a total of only 3 steps.

Modify the @SpringApplication startup class

The main class, originally annotated with @SpringBootApplication , must be modified to inherit from the SpringBootServletInitializer class.

In fact, SpringBootServletInitializer implements the WebApplicationInitializer interface, which is new in Servlet 3.0+ (JSR 315), and the implementation of this interface will automatically set the The implementation of this interface automatically configures the ServletContext and communicates with the Servlet Container, allowing the application to mount smoothly to any Application Server that supports the Servlet Container.

This mechanism is only supported from Servlet 3.0 API onwards, while Apache Tomcat supports Servlet 3.0 specification from version 7.0 onwards. If you are using Servlet 2.5 or earlier, you still need to register ApplicationContext and DispatcherServlet through web.xml . However, Apache Tomcat 7.0 is a deprecated version, so it should not be easy to encounter. For more information, see Apache Tomcat® — Which Version Do I Want?

Adjust pom.xml and change Packaging format to war

Adjust pom.xml and add spring-boot-starter-tomcat dependencies and set <scope> to provided .

The following is the current pom.xml file content.

Starting Tomcat Application Server

The following are the steps to start the Tomcat Application Server locally.

Unzip to any folder

Suppose we extract the zip to the G:\apache-tomcat-9.0.65 folder.

Starting Tomcat Server

By default, it will listen to port 8080.

Export the package file and deploy it to the Tomcat application server

Finally, we have to export a *.war file that can be deployed to Tomcat, basically the deployment steps are as follows.

Run the mvn clean package command

This command generates the target/app1-0.0.1-SNAPSHOT.war file, which is about 17MB in size.

You can unzip this war file to see its directory structure.

The most noteworthy point here is the WEB-INF/lib-provided folder. Since we have changed the <scope> of the spring-boot-starter-tomcat dependent package in pom.xml to provided, this package is moved from the default to WEB-INF/lib to the WEB-INF/lib-provided folder, which means that when we deploy to Tomcat This means that the *.jar file in the WEB-INF/lib-provided folder will not be loaded by default when we deploy to the Tomcat application server.

Copy the target/app1-0.0.1-SNAPSHOT.war file to the G:\apache-tomcat-9.0.65\webapps directory.

Wait about 1 to 3 seconds, Tomcat will automatically deploy the app1-0.0.1-SNAPSHOT.war file and automatically extract it to the app1-0.0.1-SNAPSHOT directory.

spring boot app

And we can also see the following message from the Console screen of running Tomcat.

At this point, open your browser and visit http://localhost:8080/app1-0.0.1-SNAPSHOT/ to see the application successfully deployed!

spring boot app

Modify the Context Path of the application deployed to Tomcat

Since the default WAR file name will automatically become Tomcat’s Context Path when deploying app1-0.0.1-SNAPSHOT.war to Tomcat, we can adjust the <build><finalName> setting in pom.xml to specify the final output file name. We can use $ , a built-in Maven attribute, to get the artifactId of the project as the file name.

Run mvn clean package again and the target/app1.war file will be output! ��

Addendum: If you want to specify the Context Path during the development testing phase, you can add a server.servlet.context-path=/app1 property to src/main/resources/application.properties . See: Spring Boot Change Context Path.

Technical details about the provided scope in Maven dependency management

There is one more devilish detail that I discovered when we packaged this Spring Boot application.

I originally thought that as long as the dependent package was set to <scope>provided</scope> , it would only be used during compile and test , but not actually loaded during runtime . So if it won’t be loaded, shouldn’t it theoretically be excluded from the final package *.war file, so that the overall file size of *.war can be reduced and deployed more quickly?

I found that the size of the overall *.war file does not decrease at all, and all Tomcat Embedded related files are still packed in.

war app

I also found that the app1.war file can not only be deployed to the Tomcat application server, but it can also be run independently via java -jar app1.war . In fact, it is quite convenient to think about this design, you can run it locally at any time and deploy it remotely at the same time, but the only drawback is that the file is relatively large.

I’ve spent a lot of time trying to automatically exclude Tomcat Embedded related files through the Maven build process. Then I found a way to “skip the spring-boot-maven-plugin plugin to execute the repackage target”. You just need to adjust the spring-boot-maven-plugin plugin settings.

If you want to switch the settings automatically via Spring Profiles, the complete settings are as follows.

From now on, you can run different commands and generate different WAR files based on different profiles.

To build the WAR file for the test environment, you can execute the following command.

The output of app1.war is about 17MB in size

To build a WAR file for the production environment, you can run the following command.

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

Tom Sebastian's user avatar

6 Answers 6

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.

Tom Sebastian's user avatar

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

Ali Dehghani's user avatar

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.

The annotations needed are:

Some urls may now need the root context changing to include

Hope that helps

**Steps to deploy spring boot webapp on tomcat server on local area network is as follows :-It works 100% please try it because it is implemented by myself.**strong text

add the server.port = 8080 and server.address = (your pc IP address) in your project’s application.properties file. Remember:- dont put ip address inside the brackets used here just to show the ip address inside the brackets.

Then make the war file of spring boot app you can make it in eclipse and also in VS code whatever IDE you are using.

how to generate war file in vs code:-

In the maven folder open the maven folder you will find your project and click on the folder and there is option named clean click on clean it will clean your project’s folder named as target and after this again click on the same project and below the clean you will find a option named install click on that it will freshly create your folder named as target below the src folder in your project and open this target folder you will find there two war files one is simple and other is extension having original,from these files you have to upload the war file other than the original file.

Upload the war file on tomcat server webapp folder by running the tomcat in browser and go the manager app in tomcat where you will find the option to upload the war file.

After this turn off your public firewall network from firewall and protection in windows security software in your system from the taskbar.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *