Sunday 18 October 2015

Jetty Embedded Hello World Application

We used to deploy our application in server. In some cases, we need to deploy server in our application. In this post, I am going to explain you, how to deploy Jetty in your application.
I am going to use following Maven dependency.
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-server</artifactId>
  <version>9.3.4.RC1</version>
</dependency>

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, ServletException {
    response.setContentType("text/html; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().println("<h1>Welcome to Jetty Application</h1>");
    baseRequest.setHandled(true);
  }

  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    server.setHandler(new HelloWorld());
    server.start();
    server.join();
  }
}
Run above application and hit the url ‘http://localhost:8080/’ in browser. You will get following output.
Server server = new Server(8080);
server.start();
server.join();   
Above statements create and run an HTTP server on port 8080. If you don’t set any handlers to this server, then it returns 404-error message for every request.

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
target: Represents the target of the request, usually it is an URI.
baseRequest: Jetty mutable request object
request: Immutable request object, can be wrapped by a filter or servlet.
response: response send to user, can be wrapped by a servlet/filter.

server.setHandler(new HelloWorld());
Once we add the handler to server instance, it can able to handle HTTP requests.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment