jetty
Embedding Jetty with Servlet
This is an example of how to embed Jetty server with Servlet. The Jetty Web Server provides an HTTP server and Servlet container capable of serving static and dynamic content either from a standalone or embedded instantiations. Jetty has a rich history of being embedded into a wide variety of applications. Here we will see how to deploy a servlet into jetty. The simple servlet is deployed and mounted on a context so as to be able to process requests. Embedding Jetty with Servlet implies that you should:
- Create a
HelloServlet
that extendsjavax.servlet.http.HttpServlet
and overrides itsdoGet(HttpServletRequest request, HttpServletResponse response)
method, to set the response status and the content-type. - Create a Server Object that will listen on port 8080.
- Create a
ServletContextHandler
that is backed by an instance of a Servlet and register it with the Server object. - Register the
HelloServlet
to the Server and mount it on a given context path. - Start the server.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.enterprise; 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.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; public class EmbeddingJettyWithServlet { public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/hello"); server.setHandler(context); context.addServlet(new ServletHolder(new HelloServlet()), "/*"); server.start(); } public static class HelloServlet extends HttpServlet { private static final long serialVersionUID = -6154475799000019575L; private static final String greeting = "Hello World"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(greeting); } } }
URL:
http://myhost:8080/hello/
Output:
Hello World
This was an example of how to embed Jetty with Servlet in Java.