jetty

Jetty Resource Handler Example

In this example, we will elaborate Resource Handlers in Jetty. Jetty Handlers are classes that are used for handling the incoming requests. They implement the interface org.eclipse.jetty.server.Handler on their specific purpose. Resource Handler is a specific Handler implementation whose purpose is serving static content (images, html pages or other) through a Jetty Server.

In this example, we are going to start with an Embedded Jetty example and configure it programmatically to serve static content via a Resource Handler. Later on, we are going to configure a Resource Handler through XML configuration files in a standalone Jetty server.

1. Environment

In the example, following environment will be used:

  • Java 7
  • Maven 3.x.y
  • Eclipse Luna(as the IDE)
  • Jetty v9.2.11 (In Embedded Jetty example, we will retrieve Jetty libraries through Maven)

2. Creating the Maven Project for the Embedded Example

We will create the Maven project in Eclipse, applying the steps below:

  1. Go to File -> New ->Other -> Maven Project
  2. Tick Create a simple project and press “Next”.
  3. Enter groupId as : com.javacodegeeks.snippets.enterprise
  4. Enter artifactId as : jetty-resourcehandler-example
  5. Press “Finish”.

After creating the project, we have to add following dependency to our pom.xml:

<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-server</artifactId>
			<version>9.2.11.v20150529</version>
</dependency>

3. Creating Sample Static Content

In this part, we are going to create trivial static content that is going to be served through our Embedded Jetty Server. First we have to going to create a directory in order to store the content (it is named as “Resource Base” in Jetty terminology), then we are going to put a simple text file in the in it (the content that is going to be served). The steps can be summed up as follows:

  1. Create a directory named “jcgresources” under the Eclipse project folder. That is going to be our resource base in this example.
  2. Create a text file “jcg1.txt” with some trivial content under the directory “PROJECT_BASE/jcgresources”.

Now we are good to continue with the programming part.

4. Programmatically Creating Resource Handlers in Embedded Jetty

After creating the static content, now we are going to create an embedded Jetty server programmatically. As in our previous examples, we are going to run  the Embedded Jetty within our main class in order to keep things simple.

First we are going to provide the Java source of our main class, which is decorated with comment lines. Afterwards, we are going to discuss the comment lines in order to detail our example. Below you can find the source code of the main class:

EmbeddedJettyResourceHandlerMain.java

package com.javacodegeeks.snippets.enterprise.embeddedjetty;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;


public class EmbeddedJettyResourceHandlerMain {

	public static void main(String[] args) throws Exception {
	
		Server server = new Server(8080);
		
		//1.Creating the resource handler
		ResourceHandler resourceHandler= new ResourceHandler();
		
		//2.Setting Resource Base
		resourceHandler.setResourceBase("jcgresources");

		//3.Enabling Directory Listing
		resourceHandler.setDirectoriesListed(true);
		
		//4.Setting Context Source 
		ContextHandler contextHandler= new ContextHandler("/jcg");
	
		//5.Attaching Handlers
		contextHandler.setHandler(resourceHandler);
		server.setHandler(contextHandler);

	
		// Starting the Server
		
		server.start();
		System.out.println("Started!");
		server.join();

	}
}

Now we are going to expand the commented lines:

4.1 Creating the Resource Handler

ResourceHandler  is the class that handles the requests to the static resources. It provides a number of properties to configure.

4.2 Setting Resource Base

Resource Base is the root directory of the for the static content. It is relative to the Java application. In the previous section, we had created the resource base under the Eclipse project; thus we are setting Resource Base relative to this project base. It is also possible to  set an absolute path, or a path relative to the Java classpath for the Resource Base.

4.3 Enabling Directory Listing

Directory Listing enables listing of the contents in the resource directories. It is disabled by default. When enabled, Jetty will provide a simple HTML page listing the directory content; otherwise, it will give an HTTP 403 error.

4.4 Setting Context Source

This part is optional, When we create and set a context handler, we are able to set a context root “/jcg”, so we are going to able to access our resources through http://localhost:8080/jcg. If not set, we http://localhost:8080 would point to our resource base.

4.5 Attaching Handlers

This part is a boiler plate code that attaches the handler to the server.

5. Running the Server

When we run the application, our server will start on port 8080. As mentioned above, we can access the resources through http://localhost:8080/jcg/. When we open this URL, the output will be as follows:

rh1
Figure 1: Directory listing for /jcg

Through this listing page , we can access the available resources.

6. Other Configuration

In the previous sections, we have provided sample configuration for resource handling. Jetty provides a variety of configuration options for resource handling that are not going to be detailed in this example. Some of them are:

  • Customizing the style of the directory listing with a CSS file.
  • Setting a welcome page.
  • Configuring multiple resources pages
  • Customizing the available content types

7. Standalone Jetty Example

Now we are going to configure Resource Handler for Standalone Jetty. The configuration is similar to the Embedded one, just in XML format. The steps required can be summarized as follows:

  1. Open jetty.xml file which is under JETTY_HOME/etc.
  2. Add the Resource Handler XML configuration to the handler element(which is given below)
  3. Save the file and run Jetty.

The handler element in jetty.xml seems as follows:

	<Set name="handler">
	  <New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
		<Set name="handlers">
		 <Array type="org.eclipse.jetty.server.Handler">
		  <Item>
			<New class="org.eclipse.jetty.server.handler.ContextHandler">
				  <Set name="contextPath">/jcg</Set>
				  <Set name="handler">
					  <New class="org.eclipse.jetty.server.handler.ResourceHandler">
						  <Set name="directoriesListed">true</Set>
						  <Set name="resourceBase">/Users/ibrahim/jcgexamples/jcgresources</Set>
					  </New>
				  </Set>
			</New>
		  </Item>
		   <Item>
			 <New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/>
		   </Item>
		   <Item>
			 <New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/>
		   </Item>
		  
		 </Array>
		</Set>
	  </New>
	</Set>

Here, we have set the context root as /jcg; enabled directory listing and set the resource base( but this time with an absolute path).

8. Conclusion

In this example we have configured Resource Handler for Jetty in order to serve static content. We have provided configuration both Embedded and Standalone modes of Jetty.

Download
You can download the full source code of this example here : jetty-resourcehandler-example

Ibrahim Tasyurt

Ibrahim is a Senior Software Engineer residing in Ankara,Turkey. He holds BSc and MS degrees in Computer Engineering from Middle East Technical University(METU). Throughout his professional carrier, he has worked in Enterprise Web Application projects for public sector and telecommunications domains. Java EE, Web Services and Enterprise Application Integration are the areas he is primarily involved with.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button