Sunday 18 October 2015

Jetty: Embedding connectors

Server listens on a port using connectors. In previous examples, I created server instance like below.
Server server = new Server(8080);
Above statement internally creates a default instance of a Connector that listens for requests on the port 8080.

import java.io.IOException;
import java.io.PrintWriter;

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.handler.AbstractHandler;

public class HelloHandler extends AbstractHandler {
  public HelloHandler() {

  }

  public void handle(String target, Request baseRequest,
      HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);

    PrintWriter out = response.getWriter();
    out.println("Welcome to Jetty embeddey programmng");
    baseRequest.setHandled(true);
  }
}


import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;

public class HelloWorld {

  public static void main(String[] args) throws Exception {
    Server server = new Server();

    ServerConnector http = new ServerConnector(server);
    http.setHost("127.0.0.1");
    http.setPort(8080);
    http.setIdleTimeout(30000);

    server.addConnector(http);

    server.setHandler(new HelloHandler());

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

Run above application and hit the url ‘http://localhost:8080/’ on browser. You will get following output.
ServerConnector http = new ServerConnector(server);
http.setHost("localhost");
http.setPort(8080);
http.setIdleTimeout(30000);

Above statements create a ServerConnector, that listens on port 8080 of your localhost.

server.addConnector(http);
Above statement add server connector to server.

server.setHandler(new HelloHandler());

Above statement sets handler to the server. A Handler instance is required by a Server to handle incoming HTTP requests..


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment