Jetty 9 and Hello World servlet

Posted on Sat 10 October 2015

Download and unpack jetty

wget http://ftp.heanet.ie/pub/eclipse/jetty/stable-9/dist/jetty-distribution-9.3.3.v20150827.tar.gz
tar xzf jetty-distribution-9.3.3.v20150827.tar.gz
mv jetty-distribution-9.3.3.v20150827 jetty

Prepare Demo directory

mkdir demo
cd demo
java -jar ../jetty/start.jar --add-to-startd=http,deploy
mkdir -p webapps/root/WEB-INF/classes
cd webapps/root/WEB-INF/classes/

Add webapps/root/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
  <web-app>
    <servlet>
      <servlet-name>Servlet</servlet-name>
      <servlet-class>Servlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
      <servlet-name>index</servlet-name>
      <servlet-class>Index</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
  </web-app>

Write and compile Servlet.java

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/*"}, loadOnStartup = 1)
public class Servlet extends HttpServlet 
{
  @Override 
  public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws IOException
  {
      response.getOutputStream().print("<h1>Hello World</h1>");
  }
}

Compile

javac -cp ../../../../../jetty/lib/servlet-api-3.1.jar Servlet.java
cd ../../../..

Run jetty

java -jar ../jetty/start.jar

Check

$ curl http://localhost:8080/servlet
<h1>Hello World</h1>