Don’t deploy your application in Jetty, deploy Jetty in your application!

Opublikowany

I’ve interested in Jetty web server couple years ago,
it has nice slogan „Don’t deploy your application in Jetty, deploy Jetty in your application!”.

I know that Spring Boot is fancy nowadays, but do we really need to create own stuff in fancy technologies?
Maybe we should choose good solution instead easy one?
Well I’m not telling that Spring Boot is not good, in fact I like it and use it sometimes, but it not fit to all cases.

OK if You are lazy and approve Spring stack You can use Spring Boot to all cases ;)
But I’m not and would like to have small ride with Jetty 9.

Let’s create hello world using that server.

What is Jetty, all should know – it is embedded web server which enable all including HTTP 2 capabilities to application.
Where could I get it – of course from maven central repository. I’m using Gradle and 9.4.x version in this hello ride.


compile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.4.2.v20170220'


Basic setup is quite easy

public static void main(final String... args) throws Exception {
        Server server = new Server(8080);
        server.setHandler(new IndexHandler());
        server.start();
        server.join();
}


Just create jetty server object in main method and start it. Interesting thing is being done in setHandler method.
Well first we need to explain what really handlers are in Jetty?

I treat handlers as methods for operating on requests to produce response. Simple nothing more.

So if I would like to present hello world application above IndexHandler would look like that
public class IndexHandler extends AbstractHandler {
    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);
        final PrintWriter out = response.getWriter();
        out.println("Hello from Jetty 9");
        baseRequest.setHandled(true);
    }
}

Form the official Jetty documentation [ Link ] passed parameters are:

  • baseRequest – the Jetty mutable request object, which is always unwrapped.
  • request – the immutable request object, which may have been wrapped by a filter or servlet.
  • response – the response, which may have been wrapped by a filter or servlet.

So for sure Spring Boot Hello World would be faster and containing less code, but Jetty 9 give You more freedom of choosing technology stack.

Autor
Kategorie DSP2017, Java