Java Reference
In-Depth Information
Using Jetty allows you to eliminate the drawbacks outlined previously: the JU nit test
case starts the server, you write the tests in Java in one location, and automating the
test suite is a nonissue. Thanks to Jetty's modularity, the real point of the exercise is to
stub only the Jetty handlers and not the whole server from the ground up.
6.2.2
Using Jetty as an embedded server
In order to understand how to set up and control Jetty from your tests, let's imple-
ment a simple example. Listing 6.2 shows how to start Jetty from Java and how to
define a document root (/) from which to start serving files.
Listing 6.2
Starting Jetty in embedded mode— JettySample class
[...]
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ResourceHandler
import org.mortbay.jetty.servlet.Context;
public class JettySample {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
B
C
Context root = new Context(server, "/");
root.setResourceBase("./pom.xml");
root.setHandler( new ResourceHandler());
D
server.start();
}
}
We start by creating the Jetty Server object B and specifying in the constructor which
port to listen to for HTTP requests (port 8080). Next, we create a Context object C
that processes the HTTP requests and passes them to various handlers. We map the
context to the already-created server instance and to the root (/) URL . The set-
ResourceBase method sets the document root from which to serve resources. On the
next line, we attach a ResourceHandler handler to the root to serve files from the file
system. Because this handler will return an HTTP 403-Forbidden error if we try to list
the content of a directory, we specify the resource base to be a file. In this example, we
specify the file pom.xml in the project's directory. Finally, we start the server D .
If you start the program from listing 6.2 and navigate your browser to http://
localhost:8080, you should be able to see the content of the pom.xml file (see fig-
ure 6.3).
Figure 6.3 displays the results of running the code in listing 6.2 after opening a
browser on http://localhost:8080.
Now that you've seen how to run Jetty as an embedded server, we show next how to
stub the server's resources.
 
 
 
 
 
Search WWH ::




Custom Search