В чем отличие артефакта war от war exploded
When I first started using idea, I found that every time the project modified JS or JSP page, it did not take effect, and it was really inconvenient to restart Tomcat for each modification. I think Idea must have a setting method, it is impossible to have such an inconvenient function.
It needs to be in Tomcat’s settings as:

on ‘update’ action: update shortcut key when the user is actively performing the update: Ctrl + F9
on frame deactication: update when the edit window loses focus
You can set it according to your own needs, I have both settings here.
If your project does not have the option of Update classes and resources, only the following options are available, then please continue to read, because I started like this, in this case, you can only update the changes in the classes file after updating, not update Changes in static files.

The reason for this option is that you use the option of Deployment to first make the project into a war package and then run it.

First remove the current project, add it again, select Artiface when adding

Then select the option with exploded after the project name

Select the postscript to fill in the Application context
Then change in Server to: Update classes and resources
___:war exploded
to deploy (equivalent to deploying resource files after expanding)
___:war
release mode, which is to make a war package first, and then deploy it
Advantages/Disadvantages to exploded WAR files
An answer to a question I read today suggested deploying an application as an exploded (unzipped) WAR. It got me thinking.
Every deployment I’ve ever done to a JBoss/Tomcat has been with a a WAR/EAR file. At least as far as I can remember.
Have I been making a mistake all these years?
Are there advantages to deploying an app in its expanded form rather than packaged up?
![]()
6 Answers 6
I think that was my answer mentioning the exploded WAR in the other question. Exploded WARs are easier to navigate and you can deploy ‘parts’ of your application that much quicker (depending on how our Web/App server deals with this), e.g. Replace a single resource like a JSP page. However it can have some drawbacks:
Versioning — What version are you really running? «Hmmm, I’m not really sure now»
Security — Do you have the right permissioning in place for the exploded format?
Messiness — Files galore spread out all over your nice app/web server (some people really hate this).
Bottom line: I tend to go exploded for prototype Dev work and then move to proper packaging the closer to PRD I get.
В чем отличие артефакта war от war exploded
When using IDEA development projects, the following situations usually occur when deploying Tomcat:

Is it war or war exploded? First look at the difference between the two:
War mode: upload the WEB project to the server in the form of a package;
war exploded mode: upload the WEB project to the server in the current folder position relationship;
(1) War mode This can be called the release mode. See the name and know that this is the first package and then released.
(2) War exploded mode is to directly move folders, jsp pages, classes, etc. to the Tomcat deployment folder for loading and deployment. This approach therefore supports hot deployment, which is generally used in development.
(3) In the usual development, if you use hot deployment, you should set the Tomcat accordingly, so that anything modified in the jsp interface can be displayed in time.

Modify the location of the arrow so that hot deployment can be achieved.
Pit encountered when developing with war mode
First, the location of the project code is as follows:

The above project is an SSM project.
Second, the location of the Tomcat deployed:

Third, the code used to obtain the absolute path of the context:
String contextPath = request.getSession().getServletContext().getRealPath("/");
Four, two ways of experimentation and results:
(1) When using the war mode development, obtain the relative path of the project by the following code:
The war mode is always the path obtained as follows:

among them C:\Software\apache-tomcat-8.0.32 It is the location of my Tomcat.
Can be seen through War mode It is the final package to deploy to Tomcat.
(2) Then look again War exploded mode , also set up, run the same piece of code, the results are as follows:

It can be seen that the final result is the location of my project, which is actually the location of the target of this project.
According to the experimental results of (1)(2) above, it can be seen that the deployment methods of the two methods are different, so the results obtained when obtaining the relative path of the project are different.
Сборка war-проекта
Фактически jar-библиотека – это просто zip архив, что напрямую следует из его имени: J ava Ar chive . Чаще всего он содержит просто четыре вещи:
- скомпилированные классы;
- ресурсы: properties-файлы и тому подобное;
- манифест MANIFEST.MF;
- другие jar-библиотеки (редко).
Типичная структура такого архива имеет вид:
Теперь давай рассмотрим типичный war-файл. Кстати, war не от слова война, а от W eb Ar chive . Структура war-файла обычно посложнее. Чаще всего он состоит из двух частей:
- Java-часть
- скомпилированные классы
- ресурсы для java-классов: properties-файлы и тому подобное
- другие jar-библиотеки (часто)
- манифест MANIFEST.MF
- web-xml – дескриптор развертывания веб-сервиса
- jsp-сервелеты
- статические веб-ресурсы: HTML, CSS, JS-файлы
Пример типичного war-файла:
Важно! jar-файл может запустить просто java-машина, для запуска же war-файла его нужно загрузить на веб-сервер. Самостоятельно он не запускается.
Плагин создания war-файла с помощью maven-war-plugin
Давайте представим, что у нас есть простой веб-проект. Пусть проект задается такой структурой файлов, как нам его собрать?
Во-первых, нам нужно указать Maven, собрать все это в виде war-файла , для этого есть тег <package> , пример:
Во-вторых, нам нужно подключить плагин maven-war-plugin . Пример:
Тут мы просто задаем плагин, который в будущем можно конфигурировать. Также с помощью тега webappDirectory переопределяем директорию, в которую будет развернут проект. Сейчас расскажу подробнее, о чем идет речь.
Плагину можно задать два режима сборки (два вида goal):
- war:war
- war:exploded
В первом случает итоговый war-файл просто кладется в папку target и имеет имя <artifactId>-<version>.war .
Но можно “попросить” плагин, чтобы в итоговую папку содержимое war-файла было помещено в том состоянии, в котором оно будет распаковано веб-сервером у себя внутри. Для этого используется goal war:exploded .
Второй подход используется часто, если ты запускаешь или дебажишь проект прямо из Intellij IDEA.
Кстати, тег webappDirectory в примере выше позволяет переопределить директорию куда будет распакован ваш war-файл при сборке в режиме war:exploded.
О других настройках плагина вы можете узнать из его официальной странички.
Сборка web-приложения на основе SpringBoot
Ну и хотелось бы разобрать какой-нибудь реальный пример сборки. Давай не мелочиться и рассмотрим это на примере приложения на основе SpringBoot.
Шаг первый. Создай пустой Maven web-проект с помощью IDEA.
Шаг второй. Добавь в его pom.xml зависимости от Spring.
Шаг третий. Создай класс com.javarush.spring.MainController . Его нужно разместить в папке src/main/java :
Тут описаны 3 вещи. Во-первых, аннотация @Controller указывает фреймворку SpringBoot, что этот класс будет использоваться для обслуживания входящих веб-запросов.
Во-вторых, аннотация @GetMapping , указывает, что наш метод будет вызываться для обслуживания GET-запроса на корневой URI — /
В-третьих, метод возвращает строку «index» . Это говорит фреймворку SpringBoot, что в качестве ответа нужно отдать содержимое файла index.html .
Шаг четвертый. Нужно добавить в проект файл index.html с таким содержимым:
Это не просто html. Перед тем, как его содержимое отдадут клиенту, оно будет модифицировано на сервере фреймворком Thymeleaf. В этот файл встроены специальные теги, которые позволяют библиотеке Thymeleaf обрабатывать и модифицировать содержимое страницы.
Красным отображены теги, которые будут обработаны библиотекой Thymeleaf, зеленым – стили CSS-библиотеки Bootstrap.
Шаг пятый. Задаем плагин в pom.xml:
Немного переоценил свои силы. Чтобы полностью разобрать простой пример, нужно много времени. Но ты можешь скачать полный код проекта из GitHub и попробовать разобраться в нем самостоятельно. Кстати, процентов 80% своего рабочего времени ты будешь делать именно это 🙂