Tuesday, July 30, 2013

How to embed Jetty servlet container in a application



Recently came across a requirement where in we needed a web app which contains one servlet alone.
Since it is really really small sized requirement, we didn’t wanted to invest in big web app containers.
I got to know about this servlet container called as Jetty which can be used for this purpose.
The beauty of this is you don’t need to install any web application as such (you still can if you choose to!).

All you have to do is create a project which has a servlet and Jetty jars. Once you install the process and start, it can open http port and start listening on that port for you! This is called as embedding Jetty.

I could see lot of advantages of Jetty and why one should use at below site:

The detailed reference documentation can be found at:

One sample servlet I found on net which opens up a http port and starts responding to the requests on the port:
package org.eclipse.jetty.embedded;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;

public class MinimalServlets {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletHandler handler = new ServletHandler();
        server.setHandler(handler);
        handler.addServletWithMapping(HelloServlet.class, "/*");
        server.start();
        server.join();
    }

    public static class HelloServlet extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println("<h1>Hello SimpleServlet</h1>");
        }
    }
}


No comments:

Post a Comment