Running a Servlet using Piranha is very easy and fun! For this blog entry we will show you how you can use Piranha Nano, couple with the DefaultHttpServer to run a HelloWorldServlet.
Follow steps mentioned below.
The code for the HelloWorldServlet will be similar to the snippet below.
public class HelloWorldServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter writer = response.getWriter(); writer.println("Hello World"); } }
The code for the HttpServerProcessor will be similar to the snippet below.
public class HelloWorldProcessor implements HttpServerProcessor { private final NanoPiranha piranha; public HelloWorldProcessor(NanoPiranha piranha) { this.piranha = piranha; } @Override public boolean process(HttpServerRequest request, HttpServerResponse response) { try { HttpWebApplicationRequest servletRequest = new HttpWebApplicationRequest(request); HttpWebApplicationResponse servletResponse = new HttpWebApplicationResponse(response); piranha.service(servletRequest, servletResponse); servletResponse.flush(); } catch (IOException | ServletException e) { e.printStackTrace(System.err); } return false; } }
The code for the Application class will be similar to the snippet below.
public class HelloWorldApplication { public void run() { NanoPiranha piranha = new NanoPiranhaBuilder() .servlet("HelloWorld", new HelloWorldServlet()) .build(); DefaultHttpServer server = new DefaultHttpServer(8080, new HelloWorldProcessor(piranha), false); server.start(); } public static void main(String[] arguments) throws Exception { HelloWorldApplication application = new HelloWorldApplication(); application.run(); } }
Note you can swap out DefaultHttpServer with Grizzly, JDK HTTP server, Undertow or Netty. All it takes is using the appropriate module and adjusting the class name.
The project zip is also setup to build the JLink native image, see the jlink/pom.xml file. If you want to build the project download the zip file and execute the command line below.
mvn clean verify
And voila the jlink/target/jlink
directory will contain
the JLink native image. You now have a quick recipe to write Servlets
using Piranha Nano.
Enjoy!
Posted November 23rd, 2020