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
![]()
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.
![]()
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.
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.
Spring Boot: от начала до продакшена

В данной статье я попробую расписать все шаги, которые потребуются для создания небольшого проекта на Spring Boot и развертывания его на боевом сервере.
Не будем тянуть долгими прелюдиями о философии java и spring’а, и сразу приступим к делу.
Для начала нам необходимо создать каркас приложения, внедрив туда весь необходимый зоопарк технологий(как минимум Spring, JPA, JDBC). До появления spring boot нужно было потратить на это немало времени, если конечно у вас не было рабочей заготовки в закромах кода. И именно сложность создания подобного каркаса, как мне кажется, останавливает многих от разработки небольших веб-проектов на java. Конечно, когда-то был хромой spring roo, который мог создать подобный каркас в ущерб производительности(привет аспектам), но даже с ним количество и сложность конфигурационных файлов заставляли долго медитировать над ними неподготовленного разработчика. Однако теперь с приходом Boot и Spring 4 жизнь стала немного проще и количество конфигурационных файлов заметно уменьшилось.
Если у вас есть Intellij Idea 14.1, то проблем с каркасом возникнуть вообще не должно, можно все сделать через специальный мастер создания проектов(File-New-Project. -Spring Initializr). Далее останется только указать названия проектов, выбрать интересующие нас технологии(Web, JDBC, JPA, PostgreSQL) и создать проект.
Если же у вас нет данной IDE, то скачиваем Spring Boot CLI, следуем инструкции в INSTALL.txt. Нужно задать системную переменную SPRING_HOME(путь к папке со Spring Boot, не к папке bin!) и добавить путь к SPRING_HOME/bin в системную переменную PATH на windows.
Итак, консоль спринга настроили, теперь самое время создать проект. Сделать это можно следующей командой:
UPDATE
Кроме того, как написали в комментариях, существует еще веб-конструктор: start.spring.io
Далее импортируем получившийся каркас в любимую IDE и начинаем его модифицировать под наши нужды.
Для начала добавим в каталог src/main папку webapps. Все веб-ресурсы мы будем создавать в ней, а не в папке resources, как хочет того спринг. Дело в том, что если мы будем создавать файлы в папке resources, то тогда мы лишимся возможности видеть изменения, сделанные в наших веб-ресурсах, без перезагрузки сервера. А это может быть неприятно, когда ради того, чтобы посмотреть изменившийся текст на веб-странице приходится перезапускать веб-сервер.
Теперь в папке webapps создаем файл index.html и папки css, js, font, images, в которые будем класть соответствующие ресурсы.
Для примера сделаем самый простой каркас index.html:
Изменим файл pom.xml
Должно получиться что-то подобное:
Из pom-файла мы можем увидеть следующее:
Мы используем java 8(самое время ее попробовать). Наш класс приложения называется com.yourcompany.Application(не забудьте переименовать стандартно сгенерированный класс, который может называться к примеру DemoApplication).
Мы используем postgresql 9.4(тоже неплохо бы установить его локально на свою машину). Connection pool для взаимодействия с базой данных мы берем самый модный и производительный (HikariCP). Кроме того, мы используем специальный плагин, который, когда мы будем генерировать итоговый jar’ник, перенесет все наши данные из webapp в resources/static, как того хочет spring boot. В противном случае вы не сможете увидеть все те веб-страницы, что создадите в папке webapps, когда запустите jar-ник.
Добавим пакет config и создадим в нем класс JpaConfig:
Кроме того, добавим в файл application.properties следующие строчки:
И наконец в Application.java меняем строку инициализации на следующую:
Тем самым мы настроили подключение к СУБД PostgreSQL.
Не забываем создать саму базу данных и простенькую таблицу в ней. Сделать это удобнее всего через PgAdmin.
Создав в ней пустую базу yourapp_data, выполняем скрипт создания таблицы:
Теперь настало время немного заняться начинкой нашего проекта. А именно добавить какую-нибудь сущность БД и научиться с ней работать, получая с клиента данные для ее формирования и отправляя клиенту же данные об уже созданных сущностях.
Создаем пакеты controller, entity, repository, service, utils.
В пакете entity создаем интерфейс:
Аннотации JPA и Hibernate в данном примере использовать не будем, так как эти технологии сильно замедляют работу(запрос может выполняться в 10 раз медленнее, чем на чистом jdbc), а так как у нас нет сильно сложных сущностей, для которых реально может потребоваться ORM, то воспользуемся обычным jdbcTemplate.
Создаем интерфейс репозитория:
И его реализацию:
Вместо уже упомянутого jdbcTemplate, мы, как видите, используем JdbcOperations, который является его интерфейсом. Нам приходится использовать везде интерфейсы, отделяя их от реализации, так как, во-первых это стильно, модно, молодежно, а во-вторых, spring в нашем случае использует стандартный jdk’шный Proxy для наших объектов, поэтому напрямую инжектить реализацию не получиться, пока мы не введем полноценные аспекты и AspectJ compile-time weaving. В нашем случае этого и не требуется, чтобы не перегружать приложение.
Осталось уже немного. Создаем наш сервис(мы же хорошие разработчики и должны отделить бизнес-логику от логики работы с СУБД?).
Отлично. Теперь создаем пару вспомогательных классов, необходимых для реализации контроллера:
Это наша реализация Exception’а. Может пригодиться в будущем, хотя и не обязательна, но на нее завязан следующий класс:
Если мы словили такую ошибку в нашем контроллере, то она будет обработана дополнительно в этом методе.
Наконец напишем небольшой классик, который будет формировать структуру данных для передачи на клиент:
Все, со вспомогательными классами закончили. Осталось написать наш контроллер. Он будет простым, как пробка:
В нем два метода — сохранить полученные данные и выдать порцию случайных данных на клиент. Контроллер унаследован от созданного нами ранее ExceptionHandlerController. Обработка исключений написана только как шаблон и нуждается в соответствующей доработки под себя.
Итак, основная часть серверного кода написана, осталось проверить его работу на клиенте. Для этого нужно доработать наш файл index.html и заодно добавить библиотеку jquery в каталог js.
index.html:
Да, UI получился не бог весть каким красивым, но зато с его помощью мы можем проверить работу приложения.
Запустим наш проект. В Intellij Idea это можно сделать через специальную конфигурацию запуска(Spring Boot).
Если все сделано верно, то по адресу localhost:8080 вы сможете увидеть заголовок Hello World, строку ввода и две кнопки. Попробуйте ввести что-нибудь в строку ввода и нажать на кнопку POST. Если после этого вы увидите аналогичный текст ниже поля ввода, то все работает как надо. Теперь останется модифицировать проект под свои нужды, добавить модный UI(например materializecss.com) и творить разумное, доброе, вечное.
Однако рано или поздно вы сотворите желаемое и встанет вопрос о том, как донести ваше детище в массы. Об этом будет вторая часть статьи.
Начнем с малого, но важного.
Даже если проект небольшой, все равно для него потребуется свой домен. Если вы просто обкатываете какую-нибудь идею и не хотите тратить бешеные деньги для регистрации домена на том же godaddy, то можете воспользоваться бесплатной альтернативой: freenom.com
Этот сервис позволит бесплатно зарегистрировать домен в зонах .tk, .ml, .ga, .cf, .gq
Да, не самые лучшие зоны, но: 
Далее займемся сервером, где все это будет крутиться. Так как проект у нас небольшой, то и сервер нам сгодится небольшой. В идеале хватит VPS. Достать его можно в разных местах, например www.digitalocean.com
Итак, регистрируемся, создаем самый простой дроплет и ставим на него ubuntu (в моем случае это ubuntu 12.04, дальнейшие инструкции буду описывать для этой системы, но на остальных будет примерно то же)
Отлично, у нас есть сервер, пора залить на него наш проект.
Для начала собираем проект maven’ом. Сделать это можно через IDE или же на худой конец зайдя в корневую директорию проекта и введя команду mvn clean install(путь к мавену должен быть прописан в системой переменной path на Windows). После выполнения команды собранный jar’ник помещается в локальный репозиторий (по умолчанию именуемый .m2), откуда его можно стянуть для отправки на сервер.
Для передачи файла на сервер используем WinSCP, если вы работаете под Windows.
Далее заходим на наш сервер, используя putty на Windows или ssh на Linux.
Переходим в директорию, куда был скопирован наш jar-ник и пробуем его запустить командой java -jar youapp.jar
Скорей всего, не получилось. А все почему? Наш проект был создан на java 8, а какая java стоит на сервере, можно узнать с помощью команды java -version. И скорей всего это либо 6, либо 7.
Но не будем унывать, поставим себе новую версию:
Теперь настала очередь postgres’а. До этого мы использовали локальную версию на машине разработчика, теперь пришло время поставить СУБД на сервер.
Для этого сначала выполняем магическую последовательность команд:
Далее выполняем команду входа в psql:
И выходим c помощью команды \q
Редактируем файл /etc/postgresql/9.4/main/postgresql.conf, изменив строчку #listen_addresses = ‘localhost’ на listen_addresses = ‘*’
Тем самым мы сможем подключаться к postgresql извне с помощью pgadmin’а. Хотя, конечно, желательно этого избежать в целях безопасности, и когда все будет настроено и отлажено, отключить эту возможность.
Затем редактируем файл /etc/postgresql/9.4/main/pg_hba.conf
Должны быть добавлены две новых строчки и изменена одна строка для 127.0.0.1 следующим образом:
Я намеренно изменил md5 на trust, так как лично у меня были проблемы с запуском проекта, тем самым отключив проверку пароля для заданных адресов. Возможно у вас их не будет.
Теперь все настроено. Хотя тюнинговать постгрес можно до бесконечности, но ведь у нас всего лишь маленький проект, а значит, пока оставим как есть.
Перезапускаем postgres: и проверяем его работу.
Всё, с настройкой postgres’а закончили, что у нас дальше по сценарию?
Как уже было отмечено ранее, для запуска собранного jar’ника вполне достаточно команды java -jar youapp.jar
Однако при подобном запуске для того, чтобы зайти на сайт извне, придется прописывать порт(по умолчанию 8080). Чтобы пользователи смогли зайти на сайт, просто введя его адрес, то нам потребуется прокси сервер. В качестве него можно взять nginx, который нужно будет предварительно настроить.
В моем случае корневой директорией nginx была /etc/nginx. Там нам в первую очередь потребуется изменить файл /sites_available/default следующим образом:
Однако и это еще не все. Необходимо также модифицировать наш проект, чтобы он поддерживал настроенный нами прокси. Благо сделать это не трудно, достаточно лишь в application.properties добавить строки(не забудьте залить новую версию с изменениями):
Теперь можно запустить nginx командой service nginx start и затем попробовать запустить наш проект. Он будет доступен по ссылке сайта, либо же, если вы еще не приобрели домен, то по его ip-адресу, без указания порта.
Остался еще один небольшой штрих. Немного неудобно всегда стартовать проект тем способом, который был описан выше. Неплохо бы, чтобы при старте проекта консоль ввода на сервере освобождалась, приложение не закрывалось бы после выхода из ssh-сессии и чтобы где-нибудь велись логи приложения. Сделать это можно с помощью команды nohup. Предварительно создаем bash-скрипт, называя его script.sh:
Прописываем ему право на исполнение:
И запускаем командой:
Все, приложение запущено.
Чтобы остановить приложение, можно либо воспользоваться командой pkill -9 java(при условии, что это единственное java-приложение, запущенное на сервере), либо с помощью утилиты htop, выделив этот процесс, нажав кнопку F9, выбрав слева в списке SIGKILL и нажав enter. На заметку: иногда не срабатывает с первого раза и процедуру приходится повторять.
Теперь, если все сделано правильно, можно открыть сайт нашего проекта в браузере и насладиться результатом.
Deploying Spring Boot Applications
Spring Boot 1.0 RC4 just dropped and 1.0 can’t be too far behind, and there are all sort of cool features coming!
One of the many questions I get around this concerns deployment strategies for Boot applications. Spring Boot builds on top of Spring and serves wherever Spring can serve. It enjoys Spring’s portability. Spring Boot lets the developer focus on the application’s development first, and removes the need to be overly concerned with every other aspect of its lifecycle, including deployment and management.
It aims to be production ready, out of the box. As part of this, Spring Boot does a few things differently, by default, that may be at first alien to some. In this post, I hope to briefly cover some of the common strategies for deploying a Spring Boot applications. I’ll ever so briefly introduce it, and some sample code, before we dive deeper. Feel free to skip this section and start at the Embedded Web Server Deployment section.
Getting Started with Spring Boot
If you haven’t used Spring Boot yet, do! There are many ways to get started, including the Spring Initializr at start.spring.io webservice and — if you’re using Spring Tool Suite — there’s a more familiar, integrated wizard that ultimately invokes that same webservice. I usually start by checking the Actuator, and Web checkboxes, then choosing to generate a Maven Project. This will give you two starter classes, Application.java, and ApplicationTests.java, as well as a ready-to-use Maven pom.xml file.
Here is the unzipped starter project:
The Maven build depends on Spring Boot started dependencies. These dependencies are opinionated. They bring in known, ready-to-use stacks aligned with the the task before you, not the technology stacks you might use: put another way, if you want to build a web application, then simple depend on the Spring Boot starter web dependency, like this:
The Maven build inherits information about which dependency versions to use from its parent pom , also provided by Spring Boot. You don’t need to worry about lining up common Spring project versions and third party dependencies.
The generated Java classes are boilerplate (this is why they’re generated!). You won’t often change the classes themselves, though you can. By the end of this blog you’ll have a common recipe for deploying Spring Boot applications. This is (hopefully!) the only boilerplate you’ll encounter in Spring Boot. Here is the Application.java class that Spring Boot provides:
For the purpose of demonstration during post, we’ll add in a RESTful Spring MVC controller. Here’s the revised Application.java code page complete with a Spring MVC REST controller that responds with «Hello, World» when a request to /hello/World is made:
Embedded Web Server Deployment
Out of the box, Spring Boot uses a public static void main entry-point that launches an embedded web server for you.
If you use the Maven build ( mvn clean install ) provided by the Spring Boot Initialzr, you’ll get a fat jar. This jar is handy because it includes all the other dependencies and things like your web server inside the archive. You can give anybody this one .jar and they can run your entire Spring application with no fuss: no build tool required, no setup, no web server configuration, etc: just java -jar . your.jar .
Tomcat
When you run your application, Spring Boot will detect that you have a Spring MVC controller and start up an embedded Apache Tomcat 7 instance, by default. You should be able to test the REST endpoint by opening up your browser and hitting http://localhost:8080/hello/World .
There are lots of configuration options for the embedded Tomcat. You can enable HTTPS (SSL/TLS termination) for your webservice fairly easily by providing an EmbeddedServletContainerCustomizer , as I do in this example. The module described there is a turnkey web application that can run on HTTPS, requires only a SSL/TLS certificate, and embeds its own webserver. Running that particular application is dead simple: java -Dspring.profiles.active=production -Dkeystore.file=file:///$PWD/src/main/resources/keystore.p12 -jar target/oauth-1.0.0.BUILD-SNAPSHOT.jar .
This EmbeddedServletContainerCustomizer configuration SPI lets you tap most of the power of explicit XML configuration for a standalone Apache Tomcat instance. Smaller things, like which port the server runs on, can be configured by specifying properties either through the command line (as —D -style arguments) or through a loaded property file (Spring Boot will automatically consult any properties in a file named application.properties on the CLASSPATH , for example). Thus, to change the port on which Tomcat listens, you might specify —Dserver.port=8081 , to have it listen on port 8081. If you specify server.port=0 , it’ll automatically find an unused port to listen on, instead.
By default, Spring Boot uses Tomcat 7. If you want to use Tomcat 8, just say so! You need only override the Maven build’s tomcat.version property and this will trigger the resolution of later builds of Apache Tomcat.
Jetty
Of course, some of you may want to use the Jetty embedded servlet container. Jetty’s a fine choice, as well. You can simply exclude the Spring Boot starter Tomcat module and then import the Spring Boot Starter Jetty module. Spring Boot will automatically delegate to that, instead. Here’s the revised dependencies section of our Maven build:
If you want to switch to Jetty 9, that’s easy as well. Ensure you have the following properties in your Maven build.
What about the Java EE Application Server?
But, I imagine you wondering, «how do I deploy it to an existing Tomcat installation, or to the classic Java EE application servers (some of which cost a lot of money!) like WebSphere, WebLogic, or JBoss?» Easy! It’s still just Spring, after all, so very little else is required. You’ll need to make three intuitive changes: move from a jar build to a war build in Maven: comment out the declaration of the spring-boot-maven-plugin plugin in your pom.xml file, then change the Maven packaging type to war . Finally, add a web entry point into your application. Spring configures almost everything for you using Servlet 3 Java configuration. You just need to give it the opportunity. Modify your Application entry-point class thusly:
This new base class — SpringBootServletInitializer — taps into a Servlet 3 style Java configuration API which lets you describe in code what you could only describe in web.xml before. Such configuration classes are discovered and invoked at application startup. This gives Spring Boot a chance to tell the web server about the application, including the reqired Servlet s, Filter s and Listener s typically required for the various Spring projects.
This new class can now be used to run the application using embeddedd Jetty or Tomcat, internally, and it can be deployed to any Servlet 3 container. You may experience issues if you have classes that conflict with those that ship as parter of a larger application server. In this case, use your build tool’s facilities for excluding or making optional the relevant APIs. Here are the changes to the Maven build that I had to make to get the starter Spring Boot REST service up and running on JBoss WildFly (the AS formerly known as JBoss AS):
I was then able to re-run the build and cp the built .war to the $WILDFLY_HOME/standalone/deployments directory.
Start the application server if it’s not already running, and you should then be able to bring the application up at http://localhost:8080/$YOURAPP/hello/World . Again, I’ve substituted $YOURAPP for the name of your application, as built.
To the Cloud!
No story about deployments would be complete without touching on the fastest growing deployment target today: the cloud! Of course, when we talk about cloud it helps to be specific: if you’re talking about deploying to an Amazon Web Services or a Google Compute Engine, directly, then it’s business as usual, just as though you were running the application on a Linux box on your own datacenter. Because, basically, that’s what you’re doing.
PaaS Deployment on Cloud Foundry and Heroku
If you’re trying to deploy the application to a Platform-as-a-service, Spring’s vaunted portability buys you a lot of options here. Deployment to Heroku, especially with the fat-jar approach, is the status quo for Heroku since that platform as a service expects you to bring-your-own-container, anyway! Simply put the java -jar incantation in your Procfile and you’re off to the races.
With Cloud Foundry you can deploy the application either standalone or as a .war -style web application. Once you’ve built your application (using, for example, mvn clean install ) and installed the cf command line tool, simply answer the cf push command’s prompts as I have below:
The application shoud be up and running, and accessible from http://$YOURAPP.cfapps.io/hello/Cloud%20Foundry where, again, I’ve used $YOURAPP as a placeholder for the name of your application.
Conclusion
Not bad for one little Application class and a few tweaks to a build-file!
Spring Boot aims to be production ready, by default. This means that it ships with useful defaults out of the box that may be overriden, if necessary. By default, Spring Boot provides an embedded Apache Tomcat build. By default, Spring Boot configures everything for you in a way that’s most natural from development to production in today’s platforms, as well as in the leading platforms-as-a-service.
Spring Boot provides plenty of opportunities to override the configuration, including configurable properties and customization callbacks.
Looking forward, I can already see another few posts continuing this discussion into things like management of Spring Boot applications via monitoring and management tools (JMX and JConsole, New Relic, etc.) as well as security concerns. Spring Boot, happily, provides answers for all of these concerns, and more.
Your Next Steps with Boot
The Spring Boot documentation is coming together rapidly as it moves to 1.0, and in the meantime there are many great resources to continue exploring. Check out one of my favorite grab bag pages for tips ‘n tricks, the How To document and don’t forget to check out the Spring IO guides, most of which build on Spring Boot!
I’d love to carry this discussion forward online. I want to know what other questions you want answered in your investigation of Spring Boot, so don’t be shy. I’ll be doing a virtual JUG on Spring Boot on April 9th, 2014, live! The event is worldwide and interactive, so please bring your questions, comments and feedback.
Развернуть WAR-загрузку Spring на сервере Tomcat
Spring Boot — это фреймворкconvention over configuration, который позволяет нам настроить готовую к работе настройку проекта Spring, аTomcat — один из самых популярных контейнеров сервлетов Java.
По умолчанию Spring Boot создает автономное приложение Java, которое может работать как настольное приложение или быть настроено как системная служба, но есть среды, в которых мы не можем установить новую службу или запустить приложение вручную.
В отличие от автономных приложений, Tomcat устанавливается как служба, которая может управлять несколькими приложениями в рамках одного и того же процесса приложения, избегая необходимости в конкретной настройке для каждого приложения.
В этом руководстве мы собираемся создать простое приложение Spring Boot и адаптировать его для работы в Tomcat.
2. Настройка приложения Spring Boot
Мы собираемся настроить простое веб-приложение Spring Boot, используя один из доступных начальных шаблонов:
There’s no need for additional configurations сверх стандартного@SpringBootApplication, поскольку Spring Boot позаботится о настройке по умолчанию.
Мы добавляем простую конечную точку REST, чтобы вернуть нам какой-то правильный контент:
Теперь давайте запустим приложение сmvn spring-boot:run и запустим браузер сhttp://localhost:8080/hello, чтобы проверить результаты.
3. Создание Spring Boot WAR
Контейнеры сервлетов ожидают, что приложения будут соответствовать некоторым контрактам, которые будут развернуты. Для Tomcat контракт — этоServlet API 3.0.
Чтобы наше приложение соответствовало этому контракту, мы должны выполнить несколько небольших изменений в исходном коде.
Во-первых, нам нужно упаковать приложение WAR вместо JAR. Для этого меняемpom.xml на следующее содержание:
Теперь давайте изменим окончательное имя файлаWAR, чтобы не включать номера версий:
Затем мы собираемся добавить зависимость Tomcat:
Наконец, мы инициализируем контекст сервлета, необходимый Tomcat, реализуя интерфейсSpringBootServletInitializer:
Чтобы создать наше приложение WAR, развертываемое с помощью Tomcat, мы выполняемthe mvn clean package.. После этого наш файл WAR создается вtarget/spring-boot-tomcat.war (при условии, что MavenartifactId — это «spring-boot-tomcat»).
Мы должны учитывать, что эта новая настройка делает наше приложение Spring Boot неавтономным (если вы хотите, чтобы оно снова работало в автономном режиме, удалите областьprovided из зависимости tomcat).
4. Развертывание WAR на Tomcat
Чтобы развернуть и запустить наш файл WAR в Tomcat, нам необходимо выполнить следующие шаги:
Скопируйте наш файл WAR изtarget/spring-boot-tomcat.war в папкуtomcat/webapps/
Из терминала перейдите в папкуtomcat/bin и выполните
catalina.bat run (в Windows)
catalina.sh run (в системах на базе Unix)
Это была быстрая установка Tomcat, пожалуйста, обратитесь к руководству поTomcat Installation, чтобы получить полное руководство по установке. Также есть дополнительные способыdeploying a WAR file to Tomcat.
5. Заключение
В этом кратком руководстве мы создали простое приложение Spring Boot и превратили его в действительное WAR-приложение, которое можно развернуть на сервере Tomcat.