Monday, January 19, 2015

Embedding Jetty Server: HelloWorld example

Jetty has a slogan, "Don't deploy your application into Jetty. Deploy Jetty into your application". This means that instead of bundling you application as a standard WAR deployed in Jetty, you can use Jetty server as a software component in a Java program just like any POJO.

1. Download the following JAR files:

- Jetty aggregate jar file from http://central.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/9.3.0.M1/jetty-all-9.3.0.M1.jar Jetty is decomposed into many different dependencies or JAR files. The aggregate JAR file contains all classes of the dependencies. It should not be used for production. All dependencies should be managed by Maven.

- Servlet API 3.0 from http://central.maven.org/maven2/org/eclipse/jetty/orbit/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar Please note that Jetty 9 is compatible with Servlet 3.0 so it won't work with Servlete 2.5.


2. Create handler class, HelloWorld.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class HelloWorld extends AbstractHandler {

    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletExce$
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getWriter().println("<h1>Hello World</h1>");
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        server.setHandler(new HelloWorld());
        server.start();
        server.join();
    }
}

3. Compiling

> javac -cp javax.servlet-3.0.0.v201112011016.jar:jetty-all-9.3.0.M1.jar HelloWorld.java

4. Running

> java -cp .:javax.servlet-3.0.0.v201112011016.jar:jetty-all-9.3.0.M1.jar HelloWorld.java
2015-01-04 21:15:28.066:INFO::main: Logging initialized @140ms
2015-01-04 21:15:28.175:INFO:oejs.Server:main: jetty-9.3.0.M1
2015-01-04 21:15:28.248:INFO:oejs.ServerConnector:main: Started ServerConnector@7afc02c8{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2015-01-04 21:15:28.250:INFO:oejs.Server:main: Started @329ms

Open browser and type http://localhost:8080 and then you should see "Hello World".








No comments:

Post a Comment