Menerapkan Aplikasi Web di Jetty

1. Ikhtisar

Pada artikel ini, kita akan melakukan tinjauan singkat tentang server web Jetty dan kemudian membahas berbagai pendekatan untuk menyebarkan file WAR.

Jetty adalah server web HTTP Java open source dan wadah servlet. Jetty lebih umum digunakan dalam komunikasi mesin ke mesin di ekosistem Jawa.

2. Pengaturan Proyek

Versi terbaru Jetty selalu dapat diunduh dengan mengikuti tautan ini. Kami akan membuat aplikasi web Java yang sangat dasar dari baris perintah dengan Maven, yang akan kami gunakan untuk contoh kami.

Pada artikel ini, kami menggunakan Jetty 9.x, versi terbaru saat ini.

Mari menuju ke konsol kami, arahkan ke lokasi pilihan kami dan jalankan perintah berikut:

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

Perintah ini akan membuat aplikasi web Java lengkap di dalam folder aplikasi jetty baru di lokasi kita saat ini. Ini hanyalah salah satu dari banyak cara untuk membuat aplikasi Java dengan Maven dan itu sesuai dengan tujuan kita.

Karena kita akan berurusan dengan file WAR, mari menuju ke root proyek dan membangunnya:

cd jetty-app

Membangun dengan Maven:

mvn package

Kemudian jetty-app.war akan dibuat di lokasi jetty-app / target / jetty-app.war .

3. Struktur Dermaga

Jalur konteks . Mengacu pada lokasi yang berhubungan dengan alamat server dan mewakili nama aplikasi web.

Misalnya, jika aplikasi web kita diletakkan di bawah direktori $ JETTY_HOME \ webapps \ myapp , maka akan diakses oleh URL // localhost / myapp , dan jalur konteksnya adalah / myapp .

PERANG . Adalah ekstensi dari file yang memaketkan hierarki direktori aplikasi web dalam format ZIP dan kependekan dari Arsip Web. Aplikasi web Java biasanya dikemas sebagai file WAR untuk penyebaran. File WAR dapat dibuat pada baris perintah atau dengan IDE seperti Eclipse.

4. Menerapkan dengan Menyalin WAR

Cara termudah untuk menerapkan aplikasi web ke server Jetty mungkin dengan menyalin file WAR ke direktori $ JETTY_HOME / webapps .

Setelah menyalin, kita dapat memulai server dengan menavigasi ke $ JETTY_HOME dan menjalankan perintah:

java -jar start.jar

Jetty akan memindai direktori $ JETTY_HOME / webapps saat startup untuk aplikasi web untuk diterapkan. Aplikasi baru kami akan diterapkan di / konteks aplikasi jetty .

Saat kita memuat URL // localhost: 8080 / jetty-app dari browser, kita akan melihat aplikasi kita berjalan dengan Hello world! dicetak ke layar.

5. Menerapkan Menggunakan File Konteks

Server web Jetty menawarkan cara untuk menyebarkan arsip web yang terletak di mana saja di sistem file dengan membuat file konteks untuknya.

Dengan cara ini, bahkan jika file WAR kita terletak di desktop atau kita telah memilih untuk menyimpannya di jetty-app / target dimana Maven menempatkan paketnya, kita bisa membuat file konteksnya di dalam $ JETTY_HOME / webapps .

Mari batalkan penerapan jetty-app.war yang baru saja kita terapkan dengan menghapusnya dari webapps . Kami kemudian akan membuat jetty-app.xml dengan kode berikut dan menempatkannya di dalam webapps :

   /jetty absolute/path/to/jetty-app.war 

File konteks ini harus memiliki nama yang sama dengan WAR kita , dengan ekstensi file XML. Perhatikan bahwa kita telah menyetel atribut contextPath ke / jetty . Ini berarti kita akan mengakses aplikasi web kita dari URL // localhost: 8080 / jetty .

Kemampuan untuk menyesuaikan jalur konteks ini adalah salah satu keuntungan besar dari pendekatan file konteks untuk menerapkan WAR di Jetty karena beberapa nama aplikasi mungkin tidak sesuai untuk tujuan ini.

6. Menerapkan Dengan Plugin Jetty Maven

6.1. Penerapan Default

Plugin jetty Maven membantu kita melakukan pengujian dan iterasi cepat sambil membangun aplikasi web Java. Untuk dapat menerapkan dan menjalankan aplikasi dengannya, kita hanya perlu menambahkan plugin di pom.xml :

 org.eclipse.jetty jetty-maven-plugin 9.3.11.v20160721 

Versi terbaru dapat ditemukan dengan mengikuti tautan Maven ini.

Kami harus memastikan bahwa instance Jetty kami yang berjalan pada port 8080 dihentikan sebelum kami melakukan langkah berikutnya.

Untuk menerapkan aplikasi kami setelah menambahkan plugin, kami menavigasi ke root tempat pom.xml berada dan menjalankan perintah berikut:

mvn jetty:run

Perintah ini membuat instance jetty baru, dan plugin menerapkan aplikasi ke sana. Kita bisa mengaksesnya dengan memuat // localhost: 8080.

Plugin jetty Maven terus memindai proyek web untuk mencari perubahan apa pun dan terus menerapkannya kembali.

6.2. Mengubah ContextPath

Dari sub-bagian sebelumnya, aplikasi di-deploy di bawah / konteks. Namun, jika kami ingin menerapkan di bawah jalur konteks tertentu seperti / jetty seperti sebelumnya, kami harus mengonfigurasi plugin secara berbeda.

Kami akan mengubah deklarasi plugin kami ke XML berikut:

 org.eclipse.jetty jetty-maven-plugin 9.3.11.v20160721   /jetty   

Perhatikan bagaimana kami menambahkan blok konfigurasi untuk menyesuaikan penerapan kami lebih lanjut. Beberapa opsi konfigurasi ada untuk ditempatkan di dalam blok ini tergantung pada apa yang diinginkan.

After these changes, we can re-run the plugin as before and access our app through //localhost:8080/jetty.

6.3. Changing the Port

A scenario one may face is a port in use exception. May be we have a jetty instance running on port 8080 for production, but we are still in development phase and want to benefit from the ease of iteration that comes with deploying using the Maven plugin.

In such cases, we have to run our test server on a different port. Let's change the plugin configuration to the following XML:

  /jetty   8888  

When we re-run our Maven plugin, we will be able to access our app from //localhost:8888/jetty.

It is worth noting that with the jetty Maven plugin, we do not need to have an instance of jetty installed and running. Rather, it creates its own jetty instance.

7. Deploying With Jetty Runner

Just like jetty Maven plugin, the jetty-runner offers a fast and easy way to deploy and run our web app. With jetty-runner, we also don't need to install and run a separate instance of a jetty server.

7.1. Jetty Runner Setup

To use jetty-runner in rapid deployment and running of our web apps, we can download the latest version by following this Maven link.

With jetty-runner, we only need to place its downloaded jar anywhere we please and be ready with the file system path to our web archives.

We can pass in configuration parameters from the command line as well as deploy numerous applications at different contexts and bound to different ports with just one command.

I have placed my jetty-runner jar in the same hierarchy as the jetty-app directory. That is the directory containing our web application.

7.2. Basic Deployment

Let's deploy our WAR using jetty-runner:

java -jar jetty-runner-9.4.0.M1.jar jetty-app/target/jetty-app.war

This command, just like the case of the Maven plugin, creates a jetty instance and deploys the provided WAR to it. The WAR path can be an absolute or a relative path.

We can load this application using //localhost:8080.

7.3. Deploy With Context Path

To deploy under /jetty context as before:

java -jar jetty-runner-9.4.0.M1.jar --path /jetty jetty-app/target/jetty-app.war

Accessible via //localhost:8080/jetty.

7.4. Deploy on Given Port

To deploy on a given port number:

java -jar jetty-runner-9.4.0.M1.jar --port 9090 jetty-app/target/jetty-app.war

Accessible via //localhost:9090.

7.5. Deploy Multiple WARs

To deploy several WARs with the same command, we use the –path argument to make each unique:

java -jar jetty-runner --path /one one.war --path /two two.war

We would then access one.war via //localhost:8080/one and two.war via //localhost:8080/two.

8. Deploy With Cargo Maven Plugin

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

8.1. Cargo Deployment Setup

In this section, we will look at how to use Cargo's Maven plugin to deploy a WAR to Jetty, in this case we will deploy a WAR to a Jetty 9.x 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.

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 if it was not auto created yet 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 in a plugin group in Maven's settings.xml.

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

 org.codehaus.cargo 

8.2. Local Deploying

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   jetty9x installed Insert absolute path to jetty 9 installation   existing Insert absolute path to jetty 9 installation      

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.

The latest version at the time of writing is 1.5.0. However, the latest version can always be found here. Additionally, we add a configuration section where we tell Maven that we are using Jetty container and also an existing Jetty installation.

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

By setting the configuration type to existing, we tell Maven 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 Jetty 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 deploy it by running:

mvn cargo:deploy

If all goes well in the Maven and Jetty console, then we should be able to run our web application by loading //localhost:8080/cargo-deploy.

If we check the $JETTY_HOME/webapps folder, we will find a deployment descriptor file or what we earlier on called context file called cargo-deploy.xml created by cargo.

8.3. Remote Deploying

By default, Jetty does not come with possibilities for remote deployment. In order to add such a support to Jetty, Cargo uses the Jetty remote deployer Web application.

What this means is that we have to download a web application WAR pre-created by the Cargo developers, deploy this WAR to the target jetty container.

Every time we want to deploy to this remote server using cargo Maven plugin, it will send an HTTP request to the deployer application on the remote server with our WAR for deployment.

This remote deployer can be found here. Head over to the tools section and download the cargo-jetty-7-and-onwards-deployer WAR.

Security considerations

We must set up a security realm in jetty before this can work, for authentication purposes. Create a file called realm.properties in $JETTY_HOME/etc directory of the remote jetty server. The file content is:

admin:password,manager

The admin is the user name by which the client can access the secured apps, password is the password and manager is the role the clients must possess before being granted access.

We must also declare our security requirements in the deployer application. We will unpack the WAR we downloaded from the jetty downloads page, make some changes and pack it back into a WAR.

After unpacking, head over to WEB-INF/web.xml and uncomment the XML code with the Uncomment in order to activate security comment. Or place the following code there:

  Jetty Remote Deployer /*   manager    BASIC Test Realm 

Deploying the deployer

We can now pack the app back into a WAR and copy it to any location on the remote server. We will then deploy it to Jetty.

During deployment, it is best to use a deployment descriptor file so that we can create a securityHandler and pass to it a loginService. All secured applications must have a login service, or else jetty will fail to deploy them.

Now, let us create a context file in $JETTY_HOME/webapps of the remote jetty instance, remember the rules of naming the context file. Make it the same name as the WAR:

   /deployer absolute/path/to/cargo-jetty-deployer.war    Test Realm /etc/realm.properties    

Start the remote jetty server and if everything goes well, we should be able to load //localhost:8080/cargo-jetty-deployer. We should then be able to see something like:

HTTP ERROR 400 Problem accessing /cargo-jetty-deployer/. Reason: Command / is unknown

Deploying WAR to remote Jetty

To do a remote deploy we only need to change our configuration section of pom.xml. Remote deploy means that we do not have a local installation of Jetty but have authenticated access to the deployer app running on the remote server.

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

  jetty9x remote   runtime  127.0.0.1 8080 admin password   

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

clean the project:

mvn clean

install it:

mvn install

finally, deploy it:

mvn cargo:deploy

That's it.

9. Deploying from Eclipse

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

9.1. Embedding Jetty in Eclipse

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

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 Jetty directory if not already open for us and choose the Jetty version we downloaded.

On the right side of the panel will appear a configuration page where we select the enable option to activate this Jetty version and browse to the installation folder.

From the screen shots, jetty 7.x will be replaced by the version of jetty we configured.

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.

9.2. Deploying Web Application in Embedded Jetty

To deploy a web application to the embedded Jetty instance, 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.

9.3. Deploying 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 $JETTY_HOME/webapps directory of an external Jetty installation.

10. Deploying from IntelliJ IDEA

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

10.1. Local Configuration

Open the Run menu and click the Edit Configurations options.

In the panel on the left search for Jetty Server, if it is not there click the + sign in the menu, search for Jetty and select Local. In the name field put Jetty 9.

Click the Configure… button and in Jetty 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.

Buka tab Deployment dan klik simbol +, pilih artefak yang ingin Anda tambahkan ke server dan klik OK

10.2. Konfigurasi Jarak Jauh

Ikuti petunjuk yang sama seperti untuk konfigurasi Jetty lokal tetapi di tab server, Anda harus memasukkan lokasi instalasi yang jauh.

11. Kesimpulan

Pada artikel ini, kami telah membahas secara ekstensif berbagai cara menyebarkan file WAR di server web Jetty.