How to set up your Java and Servlets development environment

In this guide we’ll cover how to set up your Java development environment for a Servlet project. We’ll also talk about a couple helpful tools that we recommend for all Java applications that use Twilio: ngrok and the Twilio Java SDK.


Let’s get started!

Choose a Java version

The latest versions of Java, 7 and 8, are the most in use nowadays. Java 8 introduced a handful of improvements over previous versions that made development in Java significantly more efficient and enjoyable. Worth mentioning are lambda expressions and the Stream API, among others.


Despite Java 8 being launched in March 2014, to date many projects are still built using Java 7. Twilio’s Java SDK supports both versions, but for new projects we recommend using Java 8.

# Check your Java version
$ java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)

If Java is already installed on your system, you can check its version by running java -version.

Install Java

How you install Java varies depending on your operating system.

Operating System Instructions
OS X You can find detailed instructions on how to install the Java SDK in the official Oracle site.
Windows Similar to OS X, the Oracle site contains the instructions on how to install the Java JDK.
Linux The exact instructions to install Java vary by distribution. You can find instructions for Ubuntu here. For other distributions please refer to Oracle.

Install an IDE

Before we can start our Java project we’ll need something to write it with.

If you already have a code writing tool of choice, you can stick with it for developing your Java application. If you're looking for something new, we recommend trying out a few options:

  • IntelliJ Idea is a fully featured Integrated Development Environment (IDE) popular for its reliability and responsiveness. Its Community distribution comes with enough features for most projects, but if you need more advanced features, you can search for a plugin or purchase the Ultimate edition.
  • Eclipse is an all-terrain IDE that can be used to develop in many languages apart from Java and can be extended through a huge amount of plugins.
  • NetBeans is an IDE with support for many common web languages out of the box, but this can be easily extended through plugins as well. Easy to use if you are new to Java.

Start a new project with Gradle

To create a new project, we can use Gradle’s ‘init --type java-library’ command which will create the basic folder structure for a Java project and will place some sample files inside:

# Create a new project named "java-twilio-sample"
$ mkdir java-twilio-sample
$ cd java-twilio-sample
$ gradle init --type java-library
:wrapper
:init

BUILD SUCCESSFUL

Total time: 0.633 secs

There is a folder missing though, and that is WEB-INF:

$ mkdir -p src/main/webapps/WEB-INF

Now create a file called web.xml inside this folder with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
        metadata-complete="true"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

   <servlet>
       <servlet-name>helloWorld</servlet-name>
       <servlet-class>guide.HelloWorldServlet</servlet-class>
   </servlet>

   <servlet-mapping>
       <servlet-name>helloWorld</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

Import javax.servlet, Jetty plugin and the Twilio Java SDK

We’re almost ready to start writing our Servlet web application, but first we need to configure Gradle to import the libraries and plugins we need. For this, open the build.gradle file located in the root folder of the project and keep on reading:

Gretty plugin

This plugin allows you to start a Jetty container and deploy our app to it using a single Gradle command. To configure it just add these two lines at the beginning of build.gradle:

apply plugin: 'war'
apply from: 'https://raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'

Now to configure the port and the context root of the Jetty instance, paste the next block of code at the end of the file:

gretty {
    port = 8080
    contextPath = '/java-guide'
}

Javax.servlet

This package is required when working with Servlets. Within the dependencies section, add the next line:

compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'

Twilio Java SDK

Finally we’ll need the the Twilio SDK. Copy and paste the next line inside the dependencies section:

compile group: 'com.twilio.sdk', name: 'twilio', version: '7.2.0'

You can see the whole build.gradle file after these modifications here. Now in a console, navigate to the project folder and run the next command:

$ gradle build

Create a simple Servlet application

We can test that our development environment is configured correctly by creating a simple Servlet application. Create a package in src/java folder named ‘guide’. Inside this folder create a Java file called HelloWorldServlet.java and paste the code below:

package guide;

import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class HelloWorldServlet extends HttpServlet {
   @Override
   public void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException {
       // Create a TwiML response and add our friendly message.
       VoiceResponse voiceResponse = new VoiceResponse.Builder()
               .say(new Say.Builder("Hello World!").build())
               .build();

       response.setContentType("application/xml");
       try {
           response.getWriter().print(voiceResponse.toXml());
       } catch (TwiMLException e) {
           e.printStackTrace();
       }
   }
}

We can then try running our new Servlet application with the command gradle appRun. You can then open http://localhost:8080/java-guide in your browser and you should see the next TwiML response : <Response><Say>Hello Monkey</Say></Response>.

Install ngrok

Once you see your sample Servlet application’s “Hello World!” message, your development environment is ready to go. But for most Twilio projects you’ll want to install one more helpful tool: ngrok.

Most Twilio services use webhooks to communicate with your application. When Twilio receives an incoming phone call, for example, it reaches out to a URL in your application for instructions on how to handle the call.

When you’re working on your Flask application in your development environment, your app is only reachable by other programs on the same computer, so Twilio won’t be able to talk to it.

Ngrok is our favorite tool for solving this problem. Once started, it provides a unique URL on the ngrok.io domain which will forward incoming requests to your local development environment.

To start, head over to the Ngrok download page and grab the binary for your operating system: https://ngrok.com/download

Once downloaded, make sure your Flask application is running and then start Ngrok using this command: "./ngrok http 8080". You should see output similar to this:

ngrok screen

Look at the “Forwarding” line to see your unique Ngrok domain name (ours is "aaf29606.ngrok.io") and then point your browser at that domain name.

If everything’s working correctly, you should see your Flask application’s “Hello World!” message displayed at your new Ngrok URL.

Anytime you’re working on your Twilio application and need a URL for a webhook you should use Ngrok to get a publicly accessible URL like this one.

Where to next?

You’re now ready to build out your Servlet application. Here are a few other resources we like:

The most relevant files of this guide

Twilio

Flask

Agustin Camino
Kevin Whinnery
Andrew Baker
David Prothero

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.