Cara Menyebarkan Fail WAR ke Tomcat

1. Gambaran keseluruhan

Apache Tomcat adalah salah satu pelayan web yang paling popular di komuniti Java. Ia dihantar sebagai wadah servlet yang mampu melayani Web ARchives dengan sambungan WAR.

Ini menyediakan papan pemuka pengurusan dari mana anda dapat menggunakan aplikasi web baru, atau membatalkan penerapan yang ada tanpa harus menghidupkan semula wadah. Ini sangat berguna dalam persekitaran pengeluaran.

Dalam artikel ini, kami akan membuat tinjauan ringkas mengenai Tomcat dan kemudian merangkumi pelbagai pendekatan untuk menyebarkan fail WAR.

2. Struktur Tomcat

Sebelum memulakan, kita harus membiasakan diri dengan beberapa istilah dan pemboleh ubah persekitaran.

2.1. Pemboleh ubah Persekitaran

Sekiranya anda pernah bekerjasama dengan Tomcat sebelum ini, ini akan sangat biasa bagi anda:

$ CATALINA_HOME

Pemboleh ubah ini menunjuk ke direktori tempat pelayan kami dipasang.

$ CATALINA_BASE

Pemboleh ubah ini menunjuk ke direktori contoh tertentu dari Tomcat, anda mungkin mempunyai beberapa contoh yang dipasang. Sekiranya pemboleh ubah ini tidak ditetapkan secara eksplisit, maka ia akan diberi nilai yang sama dengan $ CATALINA_HOME .

Aplikasi web digunakan di bawah direktori $ CATALINA_HOME \ webapps .

2.2. Terminologi

Akar dokumen . Merujuk ke direktori tingkat atas aplikasi web, di mana semua sumber aplikasi berada seperti file JSP, halaman HTML, kelas Java, dan gambar.

Jalan konteks . Merujuk ke lokasi yang relatif dengan alamat pelayan dan mewakili nama aplikasi web.

Contohnya, jika aplikasi web kita diletakkan di bawah direktori $ CATALINA_HOME \ webapps \ myapp , aplikasi tersebut akan diakses oleh URL // localhost / myapp , dan jalan konteksnya akan menjadi / myapp .

PERANG . Merupakan peluasan fail yang mengemas hierarki direktori aplikasi web dalam format ZIP dan kependekan dari Web Archive. Aplikasi web Java biasanya dikemas sebagai file WAR untuk penyebaran. Fail-fail ini dapat dibuat pada baris perintah atau dengan IDE seperti Eclipse.

Setelah menyebarkan fail WAR kami, Tomcat membongkarnya dan menyimpan semua fail projek dalam direktori webapps dalam direktori baru yang dinamakan sempena projek tersebut.

3. Persediaan Tomcat

Pelayan web Tomcat Apache adalah perisian percuma yang boleh dimuat turun dari laman web mereka. Perlu ada JDK yang tersedia di mesin pengguna dan pemboleh ubah persekitaran JAVA_HOME ditetapkan dengan betul.

3.1. Mulakan Tomcat

Kita boleh memulakan pelayan Tomcat dengan hanya menjalankan skrip permulaan yang terletak di permulaan $ CATALINA_HOME \ bin \ . Terdapat .bat dan .sh di setiap pemasangan.

Pilih pilihan yang sesuai bergantung pada sama ada anda menggunakan sistem operasi berasaskan Windows atau Unix.

3.2. Konfigurasikan Peranan

Semasa fasa penyebaran, kami akan mempunyai beberapa pilihan, salah satunya adalah dengan menggunakan papan pemuka pengurusan Tomcat. Untuk mengakses papan pemuka ini, kita mesti mempunyai pengguna admin yang dikonfigurasi dengan peranan yang sesuai.

Untuk mempunyai akses ke papan pemuka, pengguna pentadbir memerlukan peranan pengurus-gui . Kemudian, kita perlu menyebarkan fail WAR menggunakan Maven, untuk ini, kita juga memerlukan peranan skrip pengurus .

Mari buat perubahan ini pada $ CATALINA_HOME \ conf \ tomcat-users :

Maklumat lebih lanjut mengenai peranan Tomcat yang berbeza boleh didapati dengan mengikuti pautan rasmi ini.

3.3. Tetapkan Kebenaran Direktori

Akhirnya, pastikan ada kebenaran membaca / menulis pada direktori pemasangan Tomcat.

3.4. Pemasangan Ujian

Untuk menguji bahawa Tomcat disiapkan dengan betul jalankan skrip permulaan ( startup.bat / startup.sh ), jika tidak ada ralat yang dipaparkan di konsol, kita dapat memeriksa semula dengan mengunjungi // localhost: 8080 .

Sekiranya anda melihat halaman arahan Tomcat, maka kami telah memasang pelayan dengan betul.

3.5. Selesaikan Konflik Pelabuhan

Secara lalai, Tomcat diatur untuk mendengar sambungan di port 8080 . Sekiranya terdapat aplikasi lain yang sudah terikat ke port ini, konsol permulaan akan memberi tahu kami.

Untuk menukar pelabuhan, kita boleh mengedit pelayan fail konfigurasi server.xml terletak di $ CATALINA_HOME \ conf \ server.xml. Secara lalai, konfigurasi penyambung adalah seperti berikut:

Sebagai contoh, jika kita ingin menukar port kita menjadi 8081 , maka kita harus menukar atribut port penyambung seperti ini:

Kadang-kadang, port yang telah kita pilih tidak dibuka secara lalai, dalam hal ini, kita perlu membuka port ini dengan perintah yang sesuai di kernel Unix atau membuat peraturan firewall yang sesuai di Windows, bagaimana ini dilakukan di luar ruang lingkup artikel ini.

4. Sebarkan Dari Maven

Sekiranya kita ingin menggunakan Maven untuk menyebarkan arkib web kita, kita mesti mengkonfigurasi Tomcat sebagai pelayan dalam fail settings.xml Maven .

Terdapat dua lokasi di mana fail settings.xml dapat dijumpai:

  • Pemasangan The Maven: $ {maven.home} /conf/settings.xml
  • Pemasangan pengguna: $ {user.home} /. M2 / settings.xml

Setelah anda menjumpainya tambahkan Tomcat seperti berikut:

 TomcatServer admin password 

We will now need to create a basic web application from Maven to test the deployment. Let's navigate to where we would like to create the application.

Run this command on the console to create a new Java web application:

mvn archetype:generate -DgroupId=com.baeldung -DartifactId=tomcat-war-deployment -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

This will create a complete web application in the directory tomcat-war-deployment which, if we deploy now and access via the browser, prints hello world!.

But before we do that we need to make one change to enable Maven deployment. So head over to the pom.xml and add this plugin:

 org.apache.tomcat.maven tomcat7-maven-plugin 2.2  //localhost:8080/manager/text TomcatServer /myapp  

Note that we are using the Tomcat 7 plugin because it works for both versions 7 and 8 without any special changes.

The configuration url is the url to which we are sending our deployment, Tomcat will know what to do with it. The server element is the name of the server instance that Maven recognizes. Finally, the path element defines the context path of our deployment.

This means that if our deployment succeeds, we will access the web application by hitting //localhost:8080/myapp.

Now we can run the following commands from Maven.

To deploy the web app:

mvn tomcat7:deploy

To undeploy it:

mvn tomcat7:undeploy

To redeploy after making changes:

mvn tomcat7:redeploy

5. Deploy With Cargo Plugin

Cargo is a versatile library that allows us to manipulate the various type of application containers in a standard way.

5.1. Cargo Deployment Setup

In this section, we will look at how to use Cargo's Maven plugin to deploy a WAR to Tomcat, in this case, we will deploy it to a version 7 instance.

To get a firm grip on the whole process, we will start from scratch by creating a new Java web application from the command line:

mvn archetype:generate -DgroupId=com.baeldung -DartifactId=cargo-deploy -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

This will create a complete Java web application in the cargo-deploy directory. If we build, deploy and load this application as is, it will print Hello World! in the browser.

Unlike the Tomcat7 Maven plugin, the Cargo Maven plugin requires that this file is present.

Since our web application does not contain any servlets, our web.xml file will be very basic. So navigate to the WEB-INF folder of our newly created project and create a web.xml file with the following content:

  cargo-deploy  index.jsp  

To enable Maven to recognize Cargo's commands without typing the fully qualified name, we need to add the Cargo Maven plugin to a plugin group in Maven's settings.xml.

As an immediate child of the root element, add this:

 org.codehaus.cargo 

5.2. Local Deploy

In this subsection, we will edit our pom.xml to suit our new deployment requirements.

Add the plugin as follows:

   org.codehaus.cargo cargo-maven2-plugin 1.5.0   tomcat7x installed Insert absolute path to tomcat 7 installation   existing Insert absolute path to tomcat 7 installation      

The latest version, at the time of writing, is 1.5.0. However, the latest version can always be found here.

Notice that we explicitly define the packaging as a WAR, without this, our build will fail. In the plugins section, we then add the cargo maven2 plugin. Additionally, we add a configuration section where we tell Maven that we are using a Tomcat container and also an existing installation.

By setting the container type to installed, we tell Maven that we have an instance installed on the machine and we provide the absolute URL to this installation.

By setting the configuration type to existing, we tell Tomcat that we have an existing setup that we are using and no further configuration is required.

The alternative would be to tell cargo to download and setup the version specified by providing a URL. However, our focus is on WAR deployment.

It's worth noting that whether we are using Maven 2.x or Maven 3.x, the cargo maven2 plugin works for both.

We can now install our application by executing:

mvn install

and deploying it by doing:

mvn cargo:deploy

If all goes well we should be able to run our web application by loading //localhost:8080/cargo-deploy.

5.3. Remote Deploy

To do a remote deploy, we only need to change the configuration section of our pom.xml. Remote deploy means that we do not have a local installation of Tomcat but have access to the manager dashboard on a remote server.

So let's change the pom.xml so that the configuration section looks like this:

  tomcat8x remote   runtime  admin admin //localhost:8080/manager/text    

This time, we change the container type from installed to remote and the configuration type from existing to runtime. Finally, we add authentication and remote URL properties to the configuration.

Ensure that the roles and users are already present in $CATALINA_HOME/conf/tomcat-users.xml just as before.

If you are editing the same project for remote deployment, first un-deploy the existing WAR:

mvn cargo:undeploy

clean the project:

mvn clean

install it:

mvn install

finally, deploy it:

mvn cargo:deploy

That's it.

6. Deploy From Eclipse

Eclipse allows us to embed servers to add web project deployment in the normal workflow without navigating away from the IDE.

6.1. Embed Tomcat in Eclipse

We can embed an installation into eclipse by selecting the window menu item from taskbar and then preferences from the drop down.

We will find a tree grid of preference items on the left panel of the window that appears. We can then navigate to eclipse -> servers or just type servers in the search bar.

We then select the installation directory, if not already open for us, and choose the Tomcat version we downloaded.

On the right-hand-side of the panel, a configuration page will appear where we select the Enable option to activate this server version and browse to the installation folder.

We apply changes, and the next time we open the servers view from Eclipse's windows -> show view submenu, the newly configured server will be present and we can start, stop and deploy applications to it.

6.2. Deploy Web Application in Embedded Tomcat

To deploy a web application to Tomcat, it must exist in our workspace.

Open the servers view from window -> show view and look for servers. When open, we can just right click on the server we configured and select add deployment from the context menu that appears.

From the New Deployment dialog box that appears, open the project drop down and select the web project.

There is a Deploy Type section beneath the Project combo box when we select Exploded Archive(development mode), our changes in the application will be synced live without having to redeploy, this is the best option during development as it is very efficient.

Selecting Packaged Archive(production mode) will require us to redeploy every time we make changes and see them in the browser. This is best only for production, but still, Eclipse makes it equally easy.

6.3. Deploy Web Application in External Location

We usually choose to deploy a WAR through Eclipse to make debugging easier. There may come a time when we want it deployed to a location other than those used by Eclipse's embedded servers. The most common instance is where our production server is online, and we want to update the web application.

We can bypass this procedure by deploying in production mode and noting the Deploy Location in the New Deployment dialog box and picking the WAR from there.

During deployment, instead of selecting an embedded server, we can select the option from the servers view alongside the list of embedded servers. We navigate to the webapps directory of an external Tomcat installation.

7. Deploy From IntelliJ IDEA

To deploy a web application to Tomcat, it must exist and have already been downloaded and installed.

7.1. Local Configuration

Open the Run menu and click the Edit Configurations options.

In the panel on the left search for Tomcat Server, if it is not there click the + sign in the menu, search for Tomcat and select Local. In the name field put Tomcat 7/8 (depending on your version).

Click the Configure… button and in Tomcat Home field navigate to the home location of your installation and select it.

Optionally, set the Startup page to be //localhost:8080/ and HTTP port: 8080, change the port as appropriate.

Go to the Deployment tab and click on the + symbol, select artifact you want to add to the server and click OK

7.2. Remote Configuration

Follow the same instructions as for local Tomcat configurations, but in the server tab, you must enter the remote location of the installation.

8. Deploy by Copying Archive

We have seen how to export a WAR from Eclipse. One of the things we can do is to deploy it by simply dropping it into the $CATALINA_HOME\webapps directory of any Tomcat instance. If the instance is running, the deployment will start instantly as Tomcat unpacks the archive and configures its context path.

If the instance is not running, then the server will deploy the project the next time it is started.

9. Deploy From Tomcat Manager

Assuming we already have our WAR file to hand and would like to deploy it using the management dashboard. You can access the manager dashboard by visiting: //localhost:8080/manager.

The dashboard has five different sections: Manager, Applications, Deploy, Diagnostics, and Server Information. If you go to the Deploy section, you will find two subsections.

9.1. Deploy Directory or WAR File Located on Server

If the WAR file is located on the server where the Tomcat instance is running, then we can fill the required Context Path field preceded by a forward slash “/”.

Let's say we would like our web application to be accessed from the browser with the URL //localhost:8080/myapp, then our context path field will have /myapp.

We skip the XML Configuration file URL field and head over to the WAR or Directory URL field. Here we enter the absolute URL to the Web ARchive file as it appears on our server. Let's say our file's location is C:/apps/myapp.war, then we enter this location. Don't forget the WAR extension.

After that, we can click deploy button. The page will reload, and we should see the message:

OK - Deployed application at context path /myapp

at the top of the page.

Additionally, our application should also appear in the Applications section of the page.

9.2. WAR File to Deploy

Just click the choose file button, navigate to the location of the WAR file and select it, then click the deploy button.

Dalam kedua situasi tersebut, jika semuanya berjalan lancar, konsol Tomcat akan memberitahu kami bahawa penyebaran berjaya dengan mesej seperti berikut:

INFO: Deployment of web application archive \path\to\deployed_war has finished in 4,833 ms

10. Kesimpulannya

Dalam penulisan ini, kami memfokuskan penggunaan WAR ke pelayan Tomcat.