Sunday, 18 October 2015

Jetty embedding servlets


By using ServletHandler class, we can embed servlets into jetty. I used following maven dependencies for following application.
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-server</artifactId>
  <version>9.3.4.RC1</version>
</dependency>

<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-webapp</artifactId>
  <version>9.3.4.RC1</version>
</dependency>

Following steps explain, how to embed simple servlet into Jetty.

Step 1: Create simple servlet
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public HelloServlet() {
    super();
  }

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

}


Step 2: Define TestServlet class, to handle servlet requests.
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;

public class TestServlet {
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);

    handler.addServletWithMapping(HelloServlet.class, "/hello");

    server.start();
    server.join();
  }
}


handler.addServletWithMapping(HelloServlet.class, "/hello")
Above statement maps url pattern /hello to the servlet HelloServlet.

Run ‘TestServlet’ application and hit the url ‘http://localhost:8080/hello’, you will get following screen.





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment