Cómo implementar un archivo WAR en Tomcat

1. Información general

Apache Tomcat es uno de los servidores web más populares de la comunidad Java. Se envía como un contenedor de servlets capaz de servir Web ARchives con la extensión WAR.

Proporciona un panel de administración desde el que puede implementar una nueva aplicación web o anular la implementación de una existente sin tener que reiniciar el contenedor. Esto es especialmente útil en entornos de producción.

En este artículo, haremos una descripción general rápida de Tomcat y luego cubriremos varios enfoques para implementar un archivo WAR.

2. Estructura de Tomcat

Antes de comenzar, debemos familiarizarnos con alguna terminología y variables de entorno.

2.1. Variables de entorno

Si ha trabajado con Tomcat anteriormente, estos le resultarán muy familiares:

$ CATALINA_HOME

Esta variable apunta al directorio donde está instalado nuestro servidor.

$ CATALINA_BASE

Esta variable apunta al directorio de una instancia particular de Tomcat, es posible que tenga instaladas varias instancias. Si esta variable no se establece explícitamente, se le asignará el mismo valor que $ CATALINA_HOME .

Las aplicaciones web se implementan en el directorio $ CATALINA_HOME \ webapps .

2.2. Terminología

Raíz del documento . Se refiere al directorio de nivel superior de una aplicación web, donde se encuentran todos los recursos de la aplicación, como archivos JSP, páginas HTML, clases Java e imágenes.

Ruta de contexto . Se refiere a la ubicación relativa a la dirección del servidor y representa el nombre de la aplicación web.

Por ejemplo, si nuestra aplicación web se coloca en el directorio $ CATALINA_HOME \ webapps \ myapp , se accederá a ella mediante la URL // localhost / myapp , y su ruta de contexto será / myapp .

GUERRA . Es la extensión de un archivo que empaqueta una jerarquía de directorios de aplicaciones web en formato ZIP y es la abreviatura de Web Archive. Las aplicaciones web de Java generalmente se empaquetan como archivos WAR para su implementación. Estos archivos se pueden crear en la línea de comandos o con un IDE como Eclipse.

Después de implementar nuestro archivo WAR, Tomcat lo descomprime y almacena todos los archivos del proyecto en el directorio webapps en un nuevo directorio con el nombre del proyecto.

3. Configuración de Tomcat

El servidor web Tomcat Apache es un software gratuito que se puede descargar desde su sitio web. Se requiere que haya un JDK disponible en la máquina del usuario y que la variable de entorno JAVA_HOME esté configurada correctamente.

3.1. Iniciar Tomcat

Podemos iniciar el servidor Tomcat simplemente ejecutando el script de inicio ubicado en $ CATALINA_HOME \ bin \ startup . Hay un .bat y un .sh en cada instalación.

Elija la opción adecuada dependiendo de si está utilizando un sistema operativo basado en Windows o Unix.

3.2. Configurar roles

Durante la fase de implementación, tendremos algunas opciones, una de las cuales es usar el panel de administración de Tomcat. Para acceder a este tablero, debemos tener un usuario administrador configurado con los roles apropiados.

Para tener acceso al tablero, el usuario administrador necesita el rol de administrador-interfaz gráfica de usuario . Más tarde, necesitaremos implementar un archivo WAR usando Maven, para esto, también necesitamos el rol de administrador-script .

Hagamos estos cambios en $ CATALINA_HOME \ conf \ tomcat-users :

Puede encontrar más detalles sobre los diferentes roles de Tomcat siguiendo este enlace oficial.

3.3. Establecer permisos de directorio

Finalmente, asegúrese de que haya permiso de lectura / escritura en el directorio de instalación de Tomcat.

3.4. Instalación de prueba

Para probar que Tomcat está configurado correctamente, ejecute el script de inicio ( startup.bat / startup.sh ), si no se muestran errores en la consola, podemos verificarlo visitando // localhost: 8080 .

Si ve la página de inicio de Tomcat, entonces hemos instalado el servidor correctamente.

3.5. Resolver conflicto portuario

De forma predeterminada, Tomcat está configurado para escuchar las conexiones en el puerto 8080 . Si hay otra aplicación que ya está vinculada a este puerto, la consola de inicio nos lo hará saber.

Para cambiar el puerto, podemos editar el archivo de configuración del servidor server.xml ubicado en $ CATALINA_HOME \ conf \ server.xml. De forma predeterminada, la configuración del conector es la siguiente:

Por ejemplo, si queremos cambiar nuestro puerto a 8081 , entonces tendremos que cambiar el atributo de puerto del conector así:

A veces, el puerto que hemos elegido no está abierto por defecto, en este caso, necesitaremos abrir este puerto con los comandos apropiados en el kernel de Unix o creando las reglas de firewall apropiadas en Windows, cómo se hace esto está fuera del alcance de Este artículo.

4. Implementar desde Maven

Si queremos usar Maven para implementar nuestros archivos web, debemos configurar Tomcat como servidor en el archivo settings.xml de Maven .

Hay dos ubicaciones donde se puede encontrar el archivo settings.xml :

  • La instalación de Maven: $ {maven.home} /conf/settings.xml
  • Instalación de un usuario: $ {user.home} /. M2 / settings.xml

Una vez que lo haya encontrado, agregue Tomcat de la siguiente manera:

 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.

En ambas situaciones, si todo va bien, la consola de Tomcat nos informará que la implementación ha sido exitosa con un mensaje como el siguiente:

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

10. Conclusión

En este artículo, nos enfocamos en implementar un WAR en un servidor Tomcat.